如何将文本居中:在伪元素之前?

新手上路,请多包涵

我有这样的代码:

 span {
  border-radius: 50%;
  background-color: #d8d9dd;
  border: 6px solid #262c40;
  width: 25px;
  height: 25px;
  margin: 30px 0 0 40px;
  display: block;
}
span:before {
  content: attr(data-value);
  position: relative;
  white-space: pre;
  display: inline;
  top: -27px;
  left: -29px;
  width: 200px;
  text-align: center;
}
 <span data-value="November 2016"></span>
<span data-value="May 2016"></span>

如何将文本居中在 :before 伪元素位于跨度中间?可能吗?

原文由 jcubic 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 661
2 个回答

最好的办法是使用流行的定心技术相对于 span 绝对 定位 before 伪元素:

 top: 0;
left: 50%;
transform: translate(-50%, -25px);

请注意,-25px 是为了偏移圆圈上方的文本(高度为 25px) - 请参见下面的演示:

 span {
  border-radius: 50%;
  background-color: #d8d9dd;
  border: 6px solid #262c40;
  width: 25px;
  height: 25px;
  margin: 30px 0 0 40px;
  display: block;
  position:relative;
}
span:before {
  content: attr(data-value);
  position: absolute;
  white-space: pre;
  display: inline;
  top: 0;
  left: 50%;
  transform: translate(-50%, -25px);
}
 <span data-value="November 2016"></span>
<span data-value="May 2016"></span>

资源

原文由 kukkuz 发布,翻译遵循 CC BY-SA 4.0 许可协议

我们应该使用 逻辑代码,而不是任何命中和跟踪和玩弄数字!

我在伪元素中使用了 flex 以首先将其居中在 span 元素上。

然后我使用变换来 逻辑 定位伪元素。

 /*styling to just make the presentation look good*/
body{
  border:5px solid black;
  padding:50px;
  display:flex;
  flex-direction: column;
  justify-content:center;
  align-items:center;
}

/* main stylings start here*/
span {
  border-radius: 50%;
  background-color: #d8d9dd;
  border: 6px solid #262c40;
  width: 25px;
  height: 25px;
  margin: 30px 0 0 40px;
  display: block;
}
span:before {
  content: attr(data-value);
  width:150px;
  border:solid black 1px;

  /*use flex to center it to middle & upon the span*/
  display:flex;
  justify-content:center;
  align-items:center;

  /*use transform and position it LOGICALLY (by considering border widths of the parent span and ofcourse using calc() )*/
  transform: translate(calc(-50% + 2 * 6px), calc(-100% - 6px));
}
 <span data-value="November 2016"></span>
<span data-value="May 2016"></span>

我会要求使用逻辑代码而不是破坏设计的命中和跟踪值。编写响应式代码。快乐编码!

原文由 ashuvssut 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题