css - 垂直居中标题标签和标题伪选择器的内容

标签 css vertical-alignment pseudo-element

另一个垂直对齐问题...

鉴于以下情况,

HTML:

<div class="thing">
    <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et tempus mauris. Vivamus imperdiet congue iaculis.</h2>
</div>

<div class="thing">
    <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et tempus mauris.</h2>
</div>

CSS:

.thing{
    background: #eee;
    margin: 0 auto 10px;
    width: 625px
}
h2{
    display: inline-block;
    font-size: 15px;
    line-height: 20px;
    margin: 0 0 0 40px;
    vertical-align: middle;
}
.thing:before{
    background: red;
    content: '';
    display: inline-block;
    height: 40px;
    position: absolute;
    vertical-align: middle;
    width: 40px;
}

为了使文本和红色框垂直居中,我需要做什么?这应该适用于任何高度的标题。

Fiddle

最佳答案

您只需删除破坏行内 block 行为的 position:Absolute。而是使用一些技巧来 fight the space between inline-block elements并确保这两个元素可以放在容器宽度上。试试这个:

.thing{
    font-size:0; /*ADD*/
}
h2{
    /*margin: 0 0 0 40px; REMOVE*/
    width:585px; /*ADD*/
}
.thing:before{
    /*position: absolute; REMOVE*/
}

检查这个 Demo Fiddle

关于css - 垂直居中标题标签和标题伪选择器的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26631445/

相关文章:

Jquery Animate 由于某种原因无法工作

jquery - 二级伪选?

jquery - 设置 :after pseudo-element based on the parent element's width 的边框宽度

html - 垂直到水平内联对齐

html - 页脚的位置是不变的

html - Wordpress 中的子菜单项不在一行中

html - 如何将未知/动态高度的图像置于未知/动态高度的 float div 中?

css - 具有动态高度的垂直居中 Font Awesome 图标?

html - 当我的 DIV 包含图像时如何应用垂直居中?

html - CSS::before 伪元素行高?