Skip to content

Instantly share code, notes, and snippets.

@arthursvpb
Created August 8, 2022 23:14
Show Gist options
  • Save arthursvpb/b750335add131f7b8b21456d82e388ae to your computer and use it in GitHub Desktop.
Save arthursvpb/b750335add131f7b8b21456d82e388ae to your computer and use it in GitHub Desktop.
Ways to center elements in CSS
/* Grid/Flexbox */
.parent {
display: flex; /*grid*/
justify-content: center;
align-items: center;
}
/* Grid/Flexbox with margin */
.parent {
display: flex; /*grid*/
}
.child {
margin: auto;
}
/* Size is unknown */
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Known size */
.parent {
position: relative;
}
.child {
position: absolute;
--height: 100px;
--width: 200px;
height: var(--height);
width: var(--width);
top: calc(50% - var(--height) / 2);
left: calc(50% - var(--width) / 2);
}
/* Center inline content of table cell */
table td {
text-align: center;
vertical-align: middle;
}
/* Center label of a button */
.button {
--height: 30px;
height: var(--height);
line-height: var(--height);
text-align: center;
}
/* Center bg image */
.has-background {
background-image: 'url(...)';
background-repeat: no-repeat;
background-position: center;
background-size: 16px;
background-color: blue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment