Center absolute positioned elements

Sometimes you need to center an absolute positioned element, but margin: 0 auto doesn’t work. In the following example I will show you a way to center that kind of elements.

Let’s say that the HTML looks like this:

<div class="outer">
  <div class="inner"></div>
</div>

..and the CSS looks like this (for now):

.outer {
  position: relative;
  width: 300px;
  height: 300px;
  background: blue;
  margin: 100px auto;
}
.inner {
  position: absolute;
  width: 100px;
  height: 100px;
  background: yellow;
}

For now, we have the following display on the browser (the yellow div is positioned absolute):

To center the yellow div we need the following code added:

.inner {
  position: absolute;
  width: 100px;
  height: 100px;
  background: yellow;
  /* this is the new code */
  left: 0;
  right: 0;
  margin: 0 auto;
}

Now, the yellow div will look like this:

Further more, if you want it vertically align, use this:

.inner {
  position: absolute;
  width: 100px;
  height: 100px;
  background: yellow;
  left: 0;
  right: 0;
  /* this is the new code */
  margin: auto;
  top: 0;
  bottom: 0;
}

The final code will display the following:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s