【问题标题】:Div Vertical Alignment with ImagesDiv 与图像垂直对齐
【发布时间】:2013-03-06 02:05:51
【问题描述】:

我知道这已经被问过很多次了,但我仍然无法独自完成我想要的。我查看了各种网站寻求帮助,例如 HereHere 以及使用带有垂直对齐、行高等的显示表。

这是我想要完成的(我知道我可能需要添加更多 div)。文本并不总是恒定的,所以我不能只设置填充并完成它,因为红色和蓝色的文本可能会改变长度。

这是我目前拥有的一个简单的 jsFiddle:http://jsfiddle.net/gP2U8/9/

<div class="container">
    <div class="left">
        <img src="http://www.gadgets-for-men.co.uk/wp-content/themes/revolution_tech-20/images/rss-icon-50.gif" />
        <span>This is text below the image</span>
    </div>
    <div class="right">
        <span>This is text to the right of the image, will usualy contain a lot of text. This is text to the right of the image, will usualy contain a lot of text. This is text to the right of the image, will usualy contain a lot of text. This is text to the right of the image, will usualy contain a lot of text.</span>
    </div>
</div>


.container{
    border: 1px solid black;
    width: 400px;
    height: auto;
    position: relative;
    display: inline-block;
}

.left{
    float:left;
    width: 25%;
}

.right{
     float: right;
    width: 75%;
}

.left, .right{
     margin-top: 25px;
    margin-bottom: 25px;
}

【问题讨论】:

    标签: css html alignment center


    【解决方案1】:

    你离得太近了!只需将图片设置为display: block

    http://jsfiddle.net/d4DaV/1/

    【讨论】:

    • 不完全是,如果您添加更多文本,您会发现问题。 jsfiddle.net/d4DaV/2我希望下面的图片和文字也保持垂直对齐
    • 对齐在哪里?在中间?在底部?它目前在顶部对齐。
    • 垂直居中对齐,使其居中。您可以在我的模型图像中看到,左侧将停留在右侧文本的中间。
    • 这仍然是基于一个固定的百分比。它可能对你来说就足够了,但它不是居中的。
    【解决方案2】:

    您可以使用display: tabledisplay: table-cell 进行垂直对齐。

    http://jsfiddle.net/d4DaV/3/

    不适用于 IE6 和 IE7,但从 IE8 向上

    【讨论】:

      【解决方案3】:

      不要使用浮动元素。相反,使用内联元素(您可以在其上使用vertical-align 样式),将white-space: nowrapfont-size: 0 粘合在一起,如this demo fiddle 所示。

      标记(未更改):

      <div class="container">
          <div class="left"></div>
          <div class="right"></div>
      </div>
      

      样式表:

      .container{
          border: 1px solid black;
          width: 400px;
          padding: 25px 0;
          white-space: nowrap;
          font-size: 0;
      }
      .left, .right {
          display: inline-block;
          vertical-align: middle;
          white-space: normal;
          font-size: 12pt;
      }
      .left{
          width: 25%;
      }
      .right{
          width: 75%;
      }
      img {
          display: block;
      }
      

      【讨论】: