CSS: Centering
Center Horizontally
ABC
<div class="x7pn8">ABC</div>
.x7pn8 { margin-left: auto; margin-right: auto; text-align: center; border: dotted 4px red; }
Center Horizontally for position fixed element
div.x { position: fixed; top: 2px; /* moves the left edge of the element to the center of the viewport */ left: 50%; /* move it back left by half of its own width */ transform: translateX(-50%); border: solid 1px grey; }
Center Vertically using grid layout
to vertically center a text inside a block element, use grid layout
display: grid;
and
place-content: center;
.
text node is considered a anonymous element, that is why using grid on a block works to center the text inside vertically.
example
center via grid
<div class="NjC23">center via grid</div>
.NjC23 { height: 200px; width: 200px; display: grid; place-content: center; border: dotted 4px green; }
Center Vertically using flex layout
to vertically center a text inside a block element, use display: flex;
and
align-items: center;
and
justify-content: center;
.
text node is considered a anonymous element, that is why using flexbox on a block works to center the text inside vertically.
example
center via flexbox
<div class="cPr4Q">center via flexbox</div>
.cPr4Q { height: 200px; width: 200px; display: flex; align-items: center; justify-content: center; border: dotted 4px red; }