Horizontally center div using css3

February 11, 2015
by Inaam Hussain

In this tutorial will learn how to center div,span or any element horizontally using css3 in just few lines of code.

For align center we are using transform translate css property. see below image, you can see Main grey div in which one green div is align Horizontally centered.

horizontal align

horizontal align center

So, lets start with css,

CSS
.horizontal-center {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    -moz-transform: translateX(-50%); /* For mozilla support */
    -webkit-transform: translateX(-50%); /* For safari support */
    -ms-transform: translateX(-50%); /* For IE support */
    -o-transform: translateX(-50%); /* For opera support */
}

By applying position relative , left and transform we can easily align horizontally centered.

See full code with HTML & CSS

HTML & CSS
<html>
<head>
 <title>Div Align Horizontally center</title>
 <style>
.main-div {
    background: none repeat scroll 0 0 #999;
    font-size: 18px;
    height: auto;
    max-width: 850px;
    padding: 35px 15px;
}

.horizontal-center {
    background: none repeat scroll 0 0 #1fa67a;
    color: #ffffff;
    left: 50%;
    max-width: 350px;
    padding: 15px;
    position: relative;
    transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
}
 </style>
</head>
<body>
<div class="main-div">
<div class="horizontal-center">
            <span>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></div>
</div>
</body>
</html>

Hope this tutorial is helpful for you.

About

Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

4 comments

  1. |

    Can’t you just use “margin: auto;” alone for the same purpose?

    • |

      Yes we can do, by applying “margin : 0px auto;”.
      but in some cases margin doesn’t work.
      This one is just different approach for align horizontally center..

  2. |

    Good to see a different approach! Better to use “margin : 0px auto;”. But when you are using pop ups, this approach will be useful!

Leave a Comment