Horizontal Inline (texts and links etc.)
.div{
text-align: center;
}
Horizontal Block(divs and lists etc.)
.div{
margin: 0 auto;
}
Vertical Inline (texts and links etc.)
If you want to vertically align inline elements, you have two options
First one is giving equal padding-top and padding-bottom.
.text{
padding-top: 25px;
padding-bottom: 25px;
}
The second one is changing line-height equal to box height. To do that, make sure you use "white-space" is "nowrap". So, it's not going to wrap. If you want to make multiple lines and vertically align. You can still set padding-top and bottom equally.
.text{
height: 150px;
line-height: 150px;
white-space: nowrap;
}
Vertical Block (divs and tables etc.)
If you know the height of the element:
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
height: 100px; /*This height is equal to parent's height */
margin-top: -50px;
}
If you don't know the heights of the elements.
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
A better way
Don't hesitate to use flexbox and grid system. I'm using them almost for everything. Even for the simplest things. It's not going to make your website load slower. Best way to center everything and easy to handle.
Centering Horizontally
.parent{
display: flex;
justify-content: center;
}
Centering Vertically
.parent{
display: flex;
align-items: center;
}
Centering Horizontally and Vertically
.parent{
display: flex;
justify-content: center;
align-items: center;
}
Using grid to center both way
.parent{
height: 500px;
display: grid;
}
span{
margin: auto;
}
Top comments (0)