繁体   English   中英

如何水平居中图像并将其与容器底部对齐?

[英]How to center an image horizontally and align it to the bottom of the container?

如何将图像水平居中并同时对齐容器底部?

我已经能够通过自我水平居中。 我也能够通过它自己对齐容器的底部。 但我无法同时做到这两点。

这是我有的:

.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或更小。

.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>元素text-align: center ,并给它一个100%的宽度,使它的大小为.image_block

<a><img>将适当地居中。

这也有效(从这个问题中得到了暗示)

.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 */ 
}

不会

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

添加到.image_block一个img做的伎俩?
请注意,这在IE6中不起作用(可能7不确定)
你必须在.image_block上做容器Div

text-align:center;

position:relative; 也可能是一个问题。

这很棘手; 它失败的原因是你无法通过边距或文本对齐定位,而绝对定位。

如果图像在div中是单独的,那么我推荐这样的东西:

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

您可能需要在图像上粘贴vertical-align调用; 不测试就不太确定。 然而,使用vertical-alignline-height会让你感觉好多了,而不是试图搞清楚绝对定位。

删除position: relative; 线。 我不确定为什么,但它为我修复了它。

你有没有尝试过:

.image_block{
text-align: center;
vertical-align: bottom;
}
#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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM