如何垂直对齐两个div的内容?

时间:2016-05-28 00:15:49

标签: html css

我试图在我的HTML中水平对齐两个div:第一个包含图像,第二个包含文本,这是使用过的代码:



<div style="float: left; width: 55px;">
  <img src="../img/look.svg" alt="">
</div>

<div style="display: inline-block;">
  <span> Look for cases </span>
  <span> from people near you. </span>
</div>
&#13;
&#13;
&#13;

我尝试了很多方法,但是我无法将文本行放在与图像垂直轴相同的级别中,并且第二个div内的文本显示在远离图像的垂直方向上

那么,有没有可能解决这个问题?

4 个答案:

答案 0 :(得分:3)

问题在于floatvertical-align: middle; line-height: 1;将解决问题:

&#13;
&#13;
div {
  display: inline-block;
  vertical-align: top;
  line-height: 1;
}

div:first-child {
  width: 55px;
}
&#13;
<div>
  <img src="//placehold.it/50?text=DP" alt="">
</div>

<div style="display: inline-block; vertical-align: middle; line-height: 1;">
  <span> Look for cases </span>
  <span> from people near you. </span>
</div>
&#13;
&#13;
&#13;

预览

顶部对齐:

enter image description here

中间对齐:

enter image description here

vertical-align决定垂直对齐。如果您希望图片和文字位于同一行,请使用vertical-align: top

答案 1 :(得分:2)

  • 不使用内联样式
  • 不要将floatinline-block
  • 混在一起

选项#1使用float

&#13;
&#13;
div {
  float: left;
  margin-right:10px
}
&#13;
<div>
  <img src="//dummyimage.com/55x55" alt="">
</div>

<div>
  <span> Look for cases </span>
  <span> from people near you. </span>
</div>
&#13;
&#13;
&#13;

使用内联块

的选项#2

&#13;
&#13;
div {
  display:inline-block;
  vertical-align:top;
  margin-right:10px
}
&#13;
<div>
  <img src="//dummyimage.com/55x55" alt="">
</div>

<div>
  <span> Look for cases </span>
  <span> from people near you. </span>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

尝试分割CSS和HTML,不要将display:inline-blockfloat:left混合使用。在div

之后也使用clear:both
 <style>
        .fisrstDiv {
          float: left;
          display:block;
        }
         .secondDiv {
          float: left;
          display:block;
        }
      .clear {
          clear: both; 
        }
    </style>

HTML

<div class="fisrstDiv">
  <img src="//placehold.it/50?text=DP" alt="">
</div>

<div class="secondDiv">
  <span> Look for cases </span>
  <span> from people near you. </span>
</div>
<div class="clear"></div>

答案 3 :(得分:0)

.halign { display:flex; align-items: center; }救援。

我将<div class="halign"> <div style="width: 100px;"> <img src="http://lorempixel.com/100/100/" alt=""> </div> <div> <span> Look for cases </span> <span> from people near you. </span> </div> </div>添加到另一个内部,这将对齐其项目。在我的CSS中,我的图像有100px,所以我将宽度更改为100px。相应地改变你的。

Add Custom Column
Add Index Column