Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically/horizontally centering a pseudo element's generated content

Tags:

html

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!

like image 438
seeonsee Avatar asked Dec 25 '22 11:12

seeonsee


2 Answers

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>
like image 129
Josh Crozier Avatar answered Dec 27 '22 01:12

Josh Crozier


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

like image 38
Rob Erskine Avatar answered Dec 27 '22 02:12

Rob Erskine