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!
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>
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>
You can use position
just like you would on any other element. Make sure your psuedo
content has display:block;
, a defined width
and height
. From there you can give it position:relative;
and any other values you would need.
http://codepen.io/RobErskine/pen/vLYZLd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With