html - 在父 DIV 中垂直居中 CSS::after Content,带 float

标签 html css pseudo-element

::after 伪元素应用 float :向右?

我定义了以下 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. 我确实知道父 div高度。当我发布我的问题时,我忘记了我做了什么。 :)
  2. 不需要使用float,但我确实需要将“点”右对齐(根据下面的评论)。

这里有一个新的 fiddle ,高度更新:http://jsfiddle.net/EvilClosetMonkey/jR9sV/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

关于html - 在父 DIV 中垂直居中 CSS::after Content,带 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702261/

相关文章:

jquery - 如何制作 jQuery 切换?

html - 为什么 clear 不适用于这种情况?

右侧带有箭头的 CSS3 按钮(中心)

javascript - 仅使用 jquery 逐渐更改 div 颜色

css - 伪元素上的 z-Index 行为

html - hovering::before 伪元素(不是宿主元素)时如何在::after 伪元素上应用样式?

html - Paypal Express结帐实现

javascript - 如何更改悬停时的图标颜色?

jquery - 更改 JQuery 行颜色

css - 如何为 :before and :after pseudo elements? 启用 -webkit-animation/transition-property