在父DIV中使用Float在内容之后垂直居中CSS ::

时间:2014-05-16 18:27:12

标签: html css3 pseudo-element

::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的垂直中心对齐,就像文本一样?

更新

另外两条信息:

  1. 我确实知道父height的{​​{1}}。当我发布问题时,我忘记了。 :)
  2. 我不需要来使用div,但我确实需要&#39; dot&#39;与右边对齐(下面的评论)。
  3. 这里有一个新的小提琴,高度更新:http://jsfiddle.net/EvilClosetMonkey/jR9sV/2/

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;
}

Updated JSFiddle

<强>更新

以下对齐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;
}

JSFiddle Demo

答案 1 :(得分:1)

简单添加

position:absolute; top:50%;

.label-dot-1::after,然后将父级设置为相对定位

http://jsfiddle.net/FquzF/示例