Centering elements is a common task in web-development, and CSS provides several ways to achieve it. This guide will cover different techniques to center elements both horizontally and vertically.
Centering Horizontally
Using text-align
For inline elements like text, you can use the text-align
property.
.container {
text-align: center;
}
Using margin: auto
For block-level elements, you can use margin: auto
.
.element {
margin: 0 auto;
}
Using Flexbox
Flexbox is a powerful layout module that makes it easy to center elements.
.container {
display: flex;
justify-content: center;
}
Centering Vertically
Using Flexbox
Flexbox can also be used to center elements vertically.
.container {
display: flex;
align-items: center;
height: 100vh; /* Full viewport height */
}
Using Grid
CSS Grid is another powerful layout system that can center elements both horizontally and vertically.
.container {
display: grid;
place-items: center;
height: 100vh; /* Full viewport height */
}
Centering Both Horizontally and Vertically
Using Flexbox
Flexbox can center elements in both directions.
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Full viewport height */
}
Using Grid
CSS Grid can also center elements in both directions.
.container {
display: grid;
place-items: center;
height: 100vh; /* Full viewport height */
}
Conclusion
Centering elements is a fundamental skill in web-development. By using the techniques covered in this guide, you can center elements with ease using CSS.
For more information, check out the MDN Web Docs on CSS.