13

たとえば、幅が 450px の画像と、わずか 300 のコンテナーがあります。画像の幅が一定でない場合、CSS を使用してコンテナー内の画像を中央に配置することは可能ですか (一部の画像は幅が 450 の場合があります。その他 600 など)。または、JavaScript で中央に配置する必要がありますか?

4

3 に答える 3

28

これでいいの?http://jsfiddle.net/LSKRy/

<div class="outer">
    <div class="inner">
    <img src="http://3.bp.blogspot.com/-zvTnqSbUAk8/Tm49IrDAVCI/AAAAAAAACv8/05Ood5LcjkE/s1600/Ferrari-458-Italia-Nighthawk-6.jpg" alt="" />
    </div>
</div>

.outer {
    width: 300px;
    overflow: hidden;
}

.inner {
    display: inline-block;
    position: relative;
    right: -50%;
}

img {
    position: relative;
    left: -50%;
}
于 2013-02-12T17:10:12.990 に答える
2

命題 1 :

.crop {
    float:left;
    margin:.5em 10px .5em 0;
    overflow:hidden; /* this is important */
    border:1px solid #ccc;
}
/* input values to crop the image: top, right, bottom, left */
.crop img {
    margin:-20px -15px -40px -55px;
}

命題 2 :

.crop{
    float:left;
    margin:.5em 10px .5em 0;
    overflow:hidden; /* this is important */
    position:relative; /* this is important too */
    border:1px solid #ccc;
    width:150px;
    height:90px;
}
.crop img{
    position:absolute;
    top:-20px;
    left:-55px;
}

命題 3:

.crop{
    float:left;
    position:relative;
    width:150px;
    height:90px;
    border:1px solid #ccc;
    margin:.5em 10px .5em 0;
}
.crop p{
    margin:0;
    position:absolute;
    top:-20px;
    left:-55px;
    clip:rect(20px 205px 110px 55px);
}

命題 4 (ホールドスクールの効率性):

.container {
    width:400px;
    height:400px;
    margin:auto;
    overflow:hidden;
    background:transparent url(your-image-file­.img) no-repeat scroll 50% 50%;
}

もちろん、自分のニーズに合わせて.cssを調整する必要があります

続ける。

于 2013-02-12T17:14:28.807 に答える
-3

しかし、画像の一部を隠すのではなく、

<div id="container" style="width: 300px">
  <img src="yourimage" width="100%">
</div>
于 2013-02-12T17:00:31.870 に答える