是否可以在相对父<div>中对齐<img/>,而父div的宽度和高度在%?</div>

时间:2014-03-20 23:52:48

标签: css image css3 html

我们想要在水平视图中显示图像。图像的高度不相等。请检查下面的示例代码。

Fiddle: http://jsfiddle.net/QHEnL/2330/

HTML:

<div class="socialItemsContainer"> 
  <div class="socialItemContainer">
    <a href="http://www.facebook.com/photo.php?fbid=665140920189927&set=a.192940177410006.36517.167555906615100&type=1">
      <img src="http://photos-c.ak.fbcdn.net/hphotos-ak-frc3/t1/1662575_665140920189927_476265988_s.jpg">
    </a>
  </div>
  <div class="socialItemContainer">
    <a href="http://www.facebook.com/photo.php?fbid=294966490654312&set=a.159596580857971.37643.157538101063819&type=1&relevant_count=1">
      <img src="http://photos-d.ak.fbcdn.net/hphotos-ak-frc1/t1/1926912_294966490654312_427339627_s.png">
    </a>
  </div>
</div>

CSS:

.socialItemsContainer {
  display: block;
  position: relative;
  clear: both;
  overflow: hidden;
}
.socialItemsContainer .socialItemContainer {
  position: relative;
  float: left;
  width: 25%;
  padding-right: 4px;
  padding-left: 4px;
}

.socialItemsContainer .socialItemContainer img {
   width: 100%;
   height:100%;
}

我们想知道是否可以在不设置任何父div的高度的情况下,在上面的示例代码中显示所有底部对齐的图像?

我们希望看到所有图像底部对齐,如果小高度图像上方有空白,则不会出现问题。

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题:http://jsfiddle.net/QHEnL/2334/

首先将.socialItemContainer更改为display: inline-block而不是向左浮动。

接下来,由于默认情况下<a><img>元素是内嵌的,因此将它们都设置为display: block并指定vertical-align: baseline以使它们底部对齐。

.socialItemsContainer {
  display: block;
  position: relative;
  clear: both;
  overflow: hidden;
}
.socialItemsContainer .socialItemContainer {
  /* float: left; */
  display: inline-block;
  width: 25%;
  padding-right: 4px;
  padding-left: 4px;
  /* height: 100%; */
}

.socialItemContainer > a {
  display: block;
  vertical-align: baseline;
}

.socialItemsContainer .socialItemContainer img {
   width: 100%;
    display: block;
   /* height:100%; */
    vertical-align: baseline;
}

这也可以在不将链接和图像设置为display: block的情况下工作,但是您可能遇到高度/宽度的奇怪问题,因此最安全地设置该规则。

答案 1 :(得分:1)

没有设置高度?然而,这是一个棘手的问题,我想出了一个解决方案。我已经对你的CSS进行了一些更改,我添加了:

margin-top: -1000px;

.socialItemsContainer .socialItemContainer img,因为这会将我们的图像推到页面底部,假设图像高度不超过1000像素(可随意更改,只要它是负值)并且我已经还补充说:

margin-top: 100px;

.socialItemsContainer .socialItemContainer,因为这会将我们的图像向下推(因为上面的CSS将它们向上推)。我希望这是你想要的,如果你还需要其他任何东西,请随时评论。这是你的新JSFiddle:http://jsfiddle.net/QHEnL/2333/