Cheat Sheets

CSS

Created: 2019 December 7th

Updated: 2021 January 4th

Center anything, horizontally and vertically, with 3 lines of CSS:

CSS icon
.center {
display: flex;
align-items: center;
justify-content: center;
}

Via Marko ⚡ Denic

Vertically center with margin

You can use margin: auto on both display: flex and display: grid.

It will work on the child of grid or flexbox but not on a block level element.

HTML icon
<div class="margins">
<p>Pls center me!</p>
</div>
CSS icon
.margins {
/* display: flex; */
display: grid;
}
.margins p {
margin: auto;
}

Vertically center with absolute positioning

HTML icon
<div class="absolute">
<p>Pls center me!</p>
</div>
CSS icon
.absolute {
position: relative;
}
.absolute p {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
}

Vertically center with flexbox

HTML icon
<div class="flexbox">
<p>Pls center me!</p>
</div>
CSS icon
.flexbox {
display: flex;
align-items: center;
justify-content: center;
}

Vertically center with grid

Use either align-items: center; or place-items: center;

HTML icon
<div class="grid">
<p>Pls center me!</p>
</div>
CSS icon
.grid {
display: grid;
/* align-items: center; */
place-items: center;
}

Breaking Long Words and URLs

There are times when a really long string of text can overflow the container of a layout, use this:

CSS icon
.don_break_out_of_parent {
/* These are technically the same, but use both */
overflow-wrap: break-word;
word-wrap: break-word;
}