简体   繁体   English

为什么不垂直对齐? 我在div的左边

[英]Why won't this vertically align? Img to the left of div

I'm still having trouble with vertical-align, although having used it many times successfully. 尽管已成功使用了多次,但我仍然遇到垂直对齐问题。 In this case, I have an img on the left and a div on the right, here's my code: 在这种情况下,我左边有一个img,右边有一个div,这是我的代码:

 .review { font-size: 1em; } .avatarImg { float: left; width: 25%; } .reviewBlock { width: 75%; float: left; } 
 <div class="review"> <img class="avatarImg" src="http://via.placeholder.com/200x200" alt=""> <div class="reviewBlock"> <!-- misc elements --> </div> </div> 

My img is a few pixels shorter than my reviewBlock, so I would like for it to be shifted down without having to use margin-top. 我的img比我的reviewBlock短几个像素,所以我希望它可以向下移动而不必使用margin-top。 As far as I can see there is a baseline established, see these pictures. 据我所知,已建立基线,请参阅这些图片。 在此输入图像描述 在此输入图像描述

I have tried putting display:inline-block on both the img and the div, as well as vertical-align:middle and it has not done anything. 我试过在img和div上放置display:inline-block ,以及vertical-align:middle ,它没有做任何事情。 Can anyone explain what's going on here? 谁能解释一下这里发生了什么? Much thanks. 非常感谢。

Adding display: inline-block; vertical-align: middle; 添加display: inline-block; vertical-align: middle; display: inline-block; vertical-align: middle; to both elements will align them. 两个元素将对齐它们。

Make sure you also removed float , or else this won't work 确保你也删除了float ,否则这将无效

As they are inline-block I also removed the white space between the 2 by connecting them with a comment <!-- --> 由于它们是inline-block我还通过用注释<!-- -->连接它们来删除2之间的空白区域

 .review { font-size: 1em; } .avatarImg { display: inline-block; vertical-align: middle; width: 25%; } .reviewBlock { display: inline-block; vertical-align: middle; width: 75%; } 
 <div class="review"> <img class="avatarImg" src="http://placehold.it/100/f00" /><!-- --><div class="reviewBlock"> Blaa blaa<br> Blaa blaa<br> Blaa blaa<br> Blaa blaa </div> </div> 

You can also do it with the Flexbox : 您也可以使用Flexbox执行此操作

 .review { display: flex; /* or "inline-flex" / displays flex-items (children) inline */ align-items: center; /* centers them vertically */ } 
 <div class="review"> <img class="avatarImg" src="http://via.placeholder.com/200x200" alt=""> <div class="reviewBlock">This text is vertically centered.</div> </div> 

尝试将父元素与display:table和img元素放在display:table-cell和vertical-align中

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

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