垂直/水平居中伪元素的生成内容 [英] Vertically/horizontally centering a pseudo element's generated content
问题描述
我想知道是否有人可以使用任何技术来定位CSS生成的内容。例如:
I was wondering if anyone had any techniques for positioning css generated content. For example:
.block {
height: 150px;
width: 150px;
border: 1px solid black;
}
.block:after {
content: "content";
}
<div class="block"></div>
我想将内容放在框的正中央,而我通常的技巧都没有用。有任何想法吗?
谢谢!
I want to center the content in the direct center of the box and none of my usual tricks are working. Any ideas? Thanks!
推荐答案
由于伪元素本质上是作为子元素添加的,因此一种选择是使用弹性框布局。将 display:flex
添加到父元素,然后使用 align-items:center
进行垂直居中和 justify-content:center
进行水平居中。
Since pseudo elements are essentially added as children elements, one option is to use a flexbox layout. Add display: flex
to the parent element, and then use align-items: center
for vertical centering and justify-content: center
for horizontal centering.
.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 绝对定位到父元素,并使用变换技巧,用于垂直/水平居中。
Alternatively, you could also absolutely position the element relative to the parent and use the transform trick for vertical/horizontal centering.
.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>
这篇关于垂直/水平居中伪元素的生成内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!