fiddle 链接:https://jsfiddle.net/ernhep2a/2/
我试图将图像和文本居中放置在 div 的中间。当我这样做时,文本不再垂直居中,而是下降。如何实现文本垂直居中?
html:
<div>
<div class="secureHome-sessions-top-status0">
<div class="secureHome-sessions-top-status-img0"></div>
Status
</div>
</div>
<div>
<div class="secureHome-sessions-top-status">
<div class="secureHome-sessions-top-status-img"></div>
Status <!-- <-- this is not centered vertically anymore -->
</div>
</div>
CSS:
div.secureHome-sessions-top-status0 {
float:left;
width: 10%;
margin-left:2%;
height: 20px;
background:lightblue;
}
div.secureHome-sessions-top-status-img0 {
float:left;
width: 20px;
height: 20px;
background: red;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Thumbs_up_font_awesome.svg/512px-Thumbs_up_font_awesome.svg.png');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
div.secureHome-sessions-top-status {
float:left;
width: 10%;
margin-left:2%;
height: 20px;
background:lightblue;
text-align:center;
}
div.secureHome-sessions-top-status-img {
display:inline-block;
width: 20px;
height: 20px;
background: red;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Thumbs_up_font_awesome.svg/512px-Thumbs_up_font_awesome.svg.png');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
最佳答案
尝试将此 CSS 添加到您的非 float 竖起大拇指的 div 中:
vertical-align: middle;
当您将第二个 div 设置为“inline-block”时,会将 div 放置在您的文本字符串中而不是旁边。由于 div 比文本高,它会拉伸(stretch)行高,然后文本才落到位。 vertical-align:middle 将通过将您的 div 与字符串的其余部分居中来防止这种情况发生。
关于html - 垂直居中文本 : inline-block div next to text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33661333/