Position Absolute Center Horizontal Div Elements

Posted on May 7, 2015 in HTML/CSS Category with Easy Difficulty

As a lot of people doesn't know how to position absolute center horizontal div or any other html element such as lists or images without the need of any fancy 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 to build your html code (how many containers you need and how to use each one). Here is how the final work should be:

Position Absolute Center Elements with CSS

In my example I will use a main container, inside will be an image and another <div> which will be the caption of the image (a title and a description). You can read more about CSS position property here.

<div class="mainContainer">
	<img src="sunset.jpg" alt="Some Image" />

	<div class="absoluteContainer">
		<div class="imageText">
			<h2>Center Div Elements with Position Absolute</h2>
			<p>A little description for your image inside the slider</p>

The image should be normal and the caption container should be position absolute center, above our image. I will add a transparent background so you can see it better. This container will be centered horizontally using a fixed width (can be also adapted to work on responsive mobile).

Video Tutorial

You can view the video tutorial below to check how the code works live. Or you can ignore the video and read below it.

CSS to Position Absolute Center Elements Horizontally

To position absolute center an element horizontally you will need to have a fixed width container, 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 container. Here is how your CSS should look:

.mainContainer {
	position: relative;
.absoluteContainer {
	position: absolute;
	left: 0;
	right: 0;
	top: 10%;
	margin-left: auto;
 	margin-right: auto;
	max-width: 740px;

To explain the code above, the <div> with absolute position will respect the width rule or 740px or any other width you want, margins will be auto to align the element to center, but it will not work until you have left and right properties to zero.


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. Video tutorial is coming soon.

Live Demo

Download Files

Related Articles
  1. Ani says:

    Woooow, thanks :)

Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.

eight − = 5

Subscribe by E-mail

HTML-TUTS is built under the mighty WordPress platform.