Position Absolute Center Horizontal Div Elements

Lot of people search on how to position absolute center horizontal div or any other HTML element such as images without the need of Javascript or jQuery code, I will show you how to do it with CSS only.

HTML Structure

To position absolute a div horizontally in the center of another div with CSS, you must know how Position:Relative and Position:Absolute works .. any element you want to center should be in a div which style should be position:relative so that the child div (inner div) which you want to center can be  position:absolute    Here is how the final work should be:

[code]

<div class="mainContainer">

    <div class="absoluteContainer">
        <div class="images-and-Text">
            <h2>Center Div Elements with Position Absolute</h2>
    <img src="https://farm1.staticflickr.com/305/20030449231_dd7e268579_z_d.jpg" alt="Some Image" />
        </div>
    </div>
</div>

[/code]

CSS to Position Absolute Center Elements Horizontally

to have a fixed width container in pixels is better, left and right properties should be set to 0 (zero) and margins (right and left) should be set to auto.

Do not forget to add relative position to the main parent div or container. Here is how your CSS should look:

[code]

.mainContainer {
    position: relative;
}
.absoluteContainer {
    position: absolute;
    left: 0;
    right: 0;
    top: 10%;
    margin-left: auto;
     margin-right: auto;

}
.images-and-Text {text-align:center;}

[/code]

Conclusion

This trick works great even on mobile phones if you are using the correct CSS. You can use it to position absolute center horizontal your html elements inside a full width container (for example a slider with captions for every image) without any additional scripts, only pure CSS.