html - 垂直居中文本 : inline-block div next to text

标签 html css

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/

相关文章:

jquery javascript 查找元素与位置 :relative 的距离

css - 是否可以在纯 CSS 中检测 Firefox 用户?

jQuery Mobile CSS 滚动和点击

javascript - 如何使用 css3 校正鱼眼全景图?

javascript - Bootstrap 4 在单击外部/其他单选按钮时删除折叠

html - 像 MS Word 一样格式化段落

jquery - 如何垂直对齐和自定义 slider 箭头

javascript - Canvas drawImage() 不工作

html - 在删除类时反转 CSS 转换

javascript - Toggle.slide.right 不能在移动设备上正常工作