Centering all the things with CSS
·2 mins
Here are some quick ways to center most items in CSS.
Centering Text #
Text has its own property for centering.
.my-div {
text-align: center;
}
Centering block elements #
Block elements can be centered automatically by using margin: 0 auto;
.
It’s not very intuitive, but it has been the standard way of centering block elements for a long time now.
Horizontally #
<div class="container">
<div class="green"></div>
</div>
.container {
width: 100%;
height: 100%;
}
.green {
background-color: green;
width: 20%;
height: 200px;
margin: 0 auto;
}
Vertically #
.green {
background-color: green;
width: 20%;
height: 200px;
/* Use this with 'margin: 0 auto;' in order
to position within the middle of an element */
position: relative;
top: 50%;
transform: translateY(-50%);
}
Centering absolutely positioned elements #
Here’s a trick for centering absolutely positioned elements (it will also work for fixed
).
Horizontally #
<div class="container">
<div class="green"></div>
</div>
.container {
width: 100%;
height: 100%;
position: relative;
}
.green {
background-color: green;
width: 20%;
height: 200px;
position: absolute;
left: 50%;
transform: translateX(-50%);
/* For centering from the right -
right: 50%;
transform: translateX(50%); */
}
Vertically #
.green {
...
top: 50%;
transform: translateY(-50%);
/* Vertically aligning from the bottom -
bottom: 50%;
transform: translateY(50%); */
/* Aligning the middle -
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%); */
}
Vertically aligning text next to an image #
This is easily accomplished by the vertical-align
property.
img {
vertical-align: middle;
}
Any text contained within the same parent will be placed in the center next to the image.