3

に似た、画像を垂直方向に中央揃えする方法を探していtext-align centerます。text-aligncenter は、親の幅や子の幅を指定する必要がないため、かなり効率的です。コンテンツは自動的に中央に配置されます。画像を垂直に配置するためにこのようなことを行う他の方法はありますか?

4

5 に答える 5

4

あなたは2つの方法でそれを行うことができます

方法 1 (推奨)、使用display: table-cell

div {
    display: table-cell;
    height: 100px;
    border: 1px solid #f00;
    vertical-align: middle;
}

デモ


方法 2、position: absolute;andを使用して、 を使用して画像top: 50%の合計の 1/2 を差し引くheightmargin-top

div {
    height: 100px;
    border: 1px solid #f00;
    position: relative;
}

div img {
    position: absolute;
    top: 50%;
    margin-top: -24px; /* half of total height of image */
}

デモ 2

于 2013-10-01T05:54:43.520 に答える
0

親div idのparentDiv ..背景に画像を設定します

#parentDiv
{
background:url(image.png) no-repeat center center;
height:500px;
width:500px;
}

または子divでこのことを行います...

position:absolute;
   top:50%;
于 2013-10-01T05:56:01.460 に答える
0

あなたが持っているソリューションは古いブラウザでも機能しますが、近い将来 (現在、ブラウザのサポートの 70% のようになっています)、これを行うことができます。これは、はるかにシンプルでエレガントなソリューションです。

.container img{
  width: 100%;
  height: auto;
}
@supports(object-fit: cover){
    .container img{
      height: 100%;
      object-fit: cover;
      object-position: center center;
    }
}
于 2015-05-13T09:56:43.953 に答える
0
div{
    display:table-cell;
    vertical-align:middle;
}
于 2013-10-01T05:53:55.180 に答える
0

すべての真ん中に...

<div id="container">
    <div id="img"></div>
</div>

#container {
    position: relative;
    width:200px;
    height:200px;
    background:#040;
}
#container #img {
    background: url("url_to_image.jpg") no-repeat center center;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

http://jsfiddle.net/djwave28/PD6J4/

于 2013-10-01T06:10:45.823 に答える