垂直标注标题标签和标题伪选择器的内容

时间:2014-10-29 13:18:58

标签: 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

2 个答案:

答案 0 :(得分:1)

您只需删除违反内联块行为的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

答案 1 :(得分:0)

我猜你的问题有两个答案。

此解决方案一个 :(使红色框等于.thing内容的高度。

.thing{
    background: #eee;
    margin: 0 auto 10px;
    position: relative; // Make .thing:before relate it's position to this
    width: 625px
}
h2{
    font-size: 15px;
    line-height: 20px;
    margin: 0 0 0 40px;
}
.thing:before{
    background: red;
    content: '';
    height: 100%; // Height will equal .thing height
    position: absolute;
    width: 40px;
}

Demo 1

第二解决方案:(垂直设置文字中心)

.thing{
    background: #eee;
    margin: 0 auto 10px;
    min-height: 40px;
    position: relative;
    width: 625px
}

h2{
    font-size: 15px;
    line-height: 20px;
    margin: 0 0 0 40px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.thing:before{
    background: red;
    content: '';
    height: 40px;
    left: 0;
    position: absolute;
    top: 0;
    width: 40px;
}

Demo 2

相关问题