垂直/水平居中伪元素生成的内容

2024-01-07

我想知道是否有人有任何技术来定位 css 生成的内容。例如:

.block {
  height: 150px;
  width: 150px;
  border: 1px solid black;
}
.block:after {
  content: "content";
}
<div class="block"></div>

我想将内容集中在框的正中央,但我常用的技巧都不起作用。有任何想法吗? 谢谢!


由于伪元素本质上是作为子元素添加的,因此一种选择是使用弹性盒布局 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes. Add display: flex到父元素,然后使用align-items: center用于垂直居中和justify-content: center用于水平居中。

.block {
  height: 150px;
  width: 150px;
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}
.block:after {
  content: "content";
}
<div class="block"></div>

或者,您也可以绝对定位元素relative给家长并使用变换技巧 https://stackoverflow.com/questions/5703552/css-center-text-horizontal-and-vertical-inside-a-div-block/25799339#25799339用于垂直/水平居中。

.block {
  height: 150px;
  width: 150px;
  border: 1px solid black;
  position: relative;
}
.block:after {
  content: "content";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
<div class="block"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

垂直/水平居中伪元素生成的内容 的相关文章

随机推荐