CSS: Centering

By Xah Lee. Date: . Last updated: .

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

to vertically center a text inside a block element, use Flexbox Layout and specify align-items: center; and justify-content: center; .

text node is considered a anonymous element, that is why using display: flex; on a block works to center the text inside vertically.

example

ABC
<div class="cPr4Q"> ABC </div>
.cPr4Q {
 height: 200px;
 width: 200px;
 display: flex;
 align-items: center;
 justify-content: center;
 border: dotted 4px red;
}

CSS common problems