40

画像を水平方向に中央揃えし、同時にコンテナの下部に揃えるにはどうすればよいですか?

画像を水平方向に中央に配置することができました。コンテナの底を自分で揃えることもできました。しかし、私は両方を同時に行うことができませんでした。

ここに私が持っているものがあります:

.image_block {
    width: 175px;
    height: 175px;
    position: relative;
    margin: 0 auto;
}
.image_block a img {
position: absolute;
bottom: 0;
}

<div class="image_block">
    <a href="..."><img src="..." border="0"></a>
</div>

そのコードは、画像を div の下部に揃えます。画像を div 内で水平方向に中央揃えにするには、何を追加/変更する必要がありますか? 画像のサイズは事前にわかりませんが、175x175 以下になります。

4

7 に答える 7

65
.image_block    {
    width: 175px;
    height: 175px;
    position: relative;
}

.image_block a  {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0px;
}

.image_block img    {
/*  nothing specific  */
}

説明: 絶対的に配置された要素は、静的でない配置を持つ最も近い親に対して相対的になります。表示方法に満足していると思い.image_blockますので、相対的な配置はそのままにしておきます。

そのため、<a>要素は に対して相対的に配置され.image_block、下の位置合わせが得られます。次に、text-align: center要素<a>の幅を 100% にして、 のサイズにし.image_blockます。

<img>内部<a>は適切に中央に配置されます。

于 2008-11-18T19:55:32.933 に答える
24

これも機能します(この質問からヒントを得ました)

.image_block {
  height: 175px;
  width:175px;
  position:relative;
}
.image_block a img{
 margin:auto; /* Required */
 position:absolute; /* Required */
 bottom:0; /* Aligns at the bottom */
 left:0;right:0; /* Aligns horizontal center */
 max-height:100%; /* images bigger than 175 px  */
 max-width:100%;  /* will be shrinked to size */ 
}
于 2013-01-04T11:08:09.307 に答える
4

しません

margin-left:auto;
margin-right:auto;

a imgに追加され.image_blockたトリックはありますか?
それはIE6では機能しないことに注意してください(おそらく7は不明です)、コンテナDiv
で行う必要があります.image_block

text-align:center;

position:relative;問題になる可能性もあります。

于 2008-11-18T19:44:25.873 に答える
3

これは注意が必要です。失敗する理由は、絶対に配置されている間はマージンまたはテキスト整列を介して配置できないためです。

画像が div に単独である場合は、次のようなものをお勧めします。

.image_block {
    width: 175px;
    height: 175px;
    line-height: 175px;
    text-align: center;
    vertical-align: bottom;
}

vertical-align代わりに画像に呼び出しを固定する必要がある場合があります。テストしないとよくわかりません。vertical-alignただし、 andを使用するとline-height、絶対位置をいじろうとするよりもはるかにうまく処理できます。

于 2008-11-18T19:56:44.400 に答える
0

やってみました:

.image_block{
text-align: center;
vertical-align: bottom;
}
于 2008-11-18T19:55:59.703 に答える
0
#header2
{
   display: table-cell;
   vertical-align: bottom;
   background-color:Red;
}


<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
  <p>this is a test</p>
</div>
</div>
于 2015-10-07T15:49:30.987 に答える
0

行を削除しposition: relative;ます。正確な理由はわかりませんが、修正してくれます。

于 2008-11-18T19:42:02.243 に答える