There are multiple CSS properties you can choose to center your item vertically in different situations.
Let's explore it one by one.
1. line-height:
You can center your inline-element vertically by using this property like - link, text and image.
Set your line-height property value equal to the height property.
Example -
.item {
height : 100px;
line-height : 100px;
}
2. Padding:
Padding used to add the space around your content. You can use this property for multiple lines.
For centering your element vertically, give the same value to top and bottom. It will set the amount of space above and below to your content.
Example -
.item{
padding-top : 20px;
padding-bottom : 20px;
}
3. Absolute:
You can apply this property to center your block level element in vertically using position.
- Using top, bottom and auto-margin:
.parent {
position : relative;
}
.item {
position : absolute;
top : 0;
bottom : 0;
margin : auto;
}
It will work great when you know the height of the item.
.parent {
position : relative;
}
.item {
position : absolute;
top : 50%;
-webkit-transform : translateY(-50%);
transform : translateY(-50%);
}
Top:50% is relative to the parent element and transform is relative to the block you are working with.
4. Flexbox:
Make your item flex and use it with align-items to center your item vertically.
Example -
.parent {
display : flex;
align-items : center;
}
0 Comments:
Post a Comment