Reputation: 75
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!
Upvotes: 5
Views: 3692
Reputation: 11
If you're going to only have text in that block and the container will be a static size you could do something like this. I'd also recommend this article https://css-tricks.com/centering-css-complete-guide/ for more complex scenarios.
.block {
height: 150px;
width: 150px;
border: 1px solid black;
}
.block:after {
content: "content";
display:block;
width:100%;
text-align:center;
line-height:150px;
}
<div class="block"></div>
Upvotes: 1
Reputation: 241238
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>
Upvotes: 10
Reputation: 927
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
Upvotes: 1