当::after
伪元素应用::after
时,如何将float: right
伪元素生成的内容垂直居中于父元素内?
我定义了以下CSS:
.label-dot::after, .label-dot-1::after {
content: "";
border-radius: 50%;
display: inline-block;
float: right;
height: 10px;
width: 10px; }
.label-dot-1::after {
background-color: #66c2a5; }
...并将其应用于以下(测试用例)HTML:
<div style="width: 500px; background-color: red;">
<div class="label-dot-1">Neato</div>
</div>
可在此处找到测试代码的JSFiddle:http://jsfiddle.net/EvilClosetMonkey/jR9sV/
请注意,右侧的绿点与div
的顶部和右侧对齐。如何使点与div
的垂直中心对齐,就像文本一样?
更新
另外两条信息:
height
的{{1}}。当我发布问题时,我忘记了。 :)div
,但我确实需要&#39; dot&#39;与右边对齐(下面的评论)。这里有一个新的小提琴,高度更新:http://jsfiddle.net/EvilClosetMonkey/jR9sV/2/
答案 0 :(得分:2)
通过将position:relative
应用于具有已知高度的祖父元素,我们将能够绝对地将pseudo
相对于它定位,如下所示:
#container {
position:relative;
height:20px;
width: 500px;
background-color: red;
}
.label-dot-1{
}
.label-dot-1::after {
content:"";
position:absolute;
right:0;
top:5px; /* (20px - 10px)/2 */
border-radius: 50%;
display: inline-block;
height: 10px;
width: 10px;
background-color: #66c2a5;
}
<强>更新强>
以下对齐pseudo
相对于其未知高度的父级。它部分使用absolute centering technique垂直居中,然后依靠css3 calc()
函数进行正确对齐。
#container {
width: 500px;
background-color: red;
}
.label-dot-1{
position:relative;
}
.label-dot-1::after {
content:"";
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto calc(100% - 10px);
height: 10px;
width: 10px;
border-radius: 50%;
background-color: #66c2a5;
}
答案 1 :(得分:1)