Center By CSS
Posted By : Deepak Insa | 15-Dec-2014
Here I am going to describe that you can center any element by CSS anytime. I have considered nearly every situation and described solutions for all of them.
1. Hozontally center
When Inline element or text.
You can center a text or inline elements like span, a, strong etc. by using property text-align:center. This property is given to that div or box in which text or inline element is lying.
.gray-box {
text-align: center;
}
This code works on inline, inline-block and inline-table.
When block element.
You can center a block element by using margin left and right 0 but when this code is applied don't use float property.
.blue-box {
margin: 0 auto;
}
When more than one block element.
Take an outer container and keep more than one block element in it and apply this code:-
.gray-box{
text-align:center;
}
.blue-box{
display:inline-block;
text-align:left;
}
2. Vertically
When Inline element or text.
If single line text
To center a single line text line-height to be equal to height.
.gray-box{
height:80px;
line-height:80px;
}
If multiple line text
In case of multiple text line give property display: table outer container and display: table-cell; vertical-align: middle; to text.
.gray-box{
display: table;
}
.gray-box p{
display: table-cell;
vertical-align: middle;
}
When block element.
In case height is known of block element.
.gray-box{
position: relative;
}
.blue-box{
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
In case height is unknown of block element.
.gray-box{
position: relative;
}
.blue-box{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
3. Vertically and horizontally both
When element have fixed width and height.
If you know the element's height and width then you can center is by giving it negative margins of top and left half of width and height.
.gray-box{
position: relative;
}
.blue-box{
width: 300px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -150px;
}
When element have not fixed width and height.
If element width and height will be unknown then you can use transform property and negative translate 50% in both direction.
.gray-box{
position: relative;
}
.blue-box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Deepak Insa
Deepak is an experienced UI developer with experience and capabilities to build compelling UIs for Web and Mobile Applications.