17
Centering in CSS - Horizontally, Vertically
Centering Things in CSS is a bit hard. The problem is which way to reach for among the different ways available to Center Elements in CSS. In this tutorial, I have explained how to center an element with CSS Vertically, Horizontally, at Block Levels.
Centering elements horizontally is quite simple compared to vertical centering. We have present different ways to center the elements horizontally. To change the text to center horizontally is quite simple. You can simply set the text-align property to center in order to center an element horizontally.
p {
text-align: center;
}
The modern way to center anything is to use Flexbox rather than going with the text.
#mysection {
display: flex;
justify-content: center;
}
Any element within my section will be centered horizontally by using the above code. There is an alternative method to go with if you don't want to use the flexbox.
Anything which is not text can be centered by applying an automatic margin on the left and right and set the width of the element.
section {
margin: 0 auto;
width: 50%;
}
The above margin: 0 auto;
is a shorthand for
section {
margin-top: 0;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
}
Do remember to set the item to display: block
if it is an inline element.
Centering an element vertically can be a difficult task. Flexbox gives us a simple way to center alignment vertically.
#mysection {
display: flex;
align-items: center;
}
Any element within my section will be centered vertically.
You can combine the flexbox techniques to center both vertically and horizontally for an element in the page.
#mysection {
display: flex;
align-items: center;
justify-content: center;
}
We can perform the same using CSS Grid:
body {
display: grid;
place-items: center;
height: 100vh;
}
17