[css] Center an element with "absolute" position and undefined width in CSS?

I need to place a div (with position:absolute;) element in the center of my window. But I am having problems doing so, because the width is unknown.

I tried this. But it needs to be adjusted as the width is responsive.

.center {
  left: 50%;
  bottom: 5px;
}

How can I do it?

This question is related to css css-position center absolute

The answer is


This worked for me:

<div class="container><p>My text</p></div>

.container{
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}

This works for vertical and horizontal:

#myContent{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

And if you want make an element center of the parent, set the position of the parent relative:

#parentElement{
    position: relative
}
  • For vertical center align, set the height to your element. Thanks to Raul.

  • If you want make an element center of the parent, set the position of the parent to relative


Responsive solution

Assuming the element in the div, is another div...

This solution works fine:

<div class="container">
  <div class="center"></div>
</div>

The container can be any size (must be position relative):

.container {
    position: relative; /* Important */
    width: 200px; /* Any width */
    height: 200px; /* Any height */
    background: red;
}

The element (div) can also be any size (must be smaller than the container):

.center {
    position: absolute; /* Important */
    top: 50%; /* Position Y halfway in */
    left: 50%; /* Position X halfway in */
    transform: translate(-50%,-50%); /* Move it halfway back(x,y) */
    width: 100px; /* Any width */
    height: 100px; /* Any height */
    background: blue;
}

The result will look like this. Run the code snippet:

_x000D_
_x000D_
.container {
    position: relative;
    width: 200px;
    height: 200px;
    background: red;
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100px;
    height: 100px;
    background: blue;
}
_x000D_
<div class="container">
    <div class="center"></div>
</div>
_x000D_
_x000D_
_x000D_

I found it very helpful.


Responsive Solution

Here is a good solution for responsive design or unknown dimensions in general if you don't need to support IE8 and lower.

.centered-axis-x {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}

_x000D_
_x000D_
.outer {
    position: relative; /* or absolute */
    
    /* unnecessary styling properties */
    margin: 5%;
    width: 80%;
    height: 500px;
    border: 1px solid red;
}

.inner {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    
    /* unnecessary styling properties */
    max-width: 50%;
    text-align: center;
    border: 1px solid blue;
}
_x000D_
<div class="outer">
    <div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS Fiddle

The clue is, that left: 50% is relative to the parent while the translate transform is relative to the elements width/height.

This way you have a perfectly centered element, with a flexible width on both child and parent. Bonus: this works even if the child is bigger than the parent.

You can also center it vertically with this (and again, width and height of parent and child can be totally flexible (and/or unknown)):

.centered-axis-xy {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

Keep in mind that you might need transform vendor prefixed as well. For example -webkit-transform: translate(-50%,-50%);


Flexbox can be used to center an absolute positioned div.

display: flex;
align-items: center;
justify-content: center;

_x000D_
_x000D_
.relative {
  width: 275px;
  height: 200px;
  background: royalblue;
  color: white;
  margin: auto;
  position: relative;
}

.absolute-block {
  position: absolute;
  height: 36px;
  background: orange;
  padding: 0px 10px;
  bottom: -5%;
  border: 1px solid black;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 10px 2px rgba(0, 0, 0, 0.3);
}
_x000D_
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
#content { margin:0 auto; display:table; float:none;}
_x000D_
<body>_x000D_
  <div>_x000D_
    <div id="content">_x000D_
      I'm the content_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_


None of the solutions worked for me since I didn't want to change the styling of the container/wrapper element. This code worked for me:

position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;

As far as I know, this is impossible to achieve for an unknown width.

You could - if that works in your scenario - absolutely position an invisible element with 100% width and height, and have the element centered in there using margin: auto and possibly vertical-align. Otherwise, you'll need JavaScript to do that.


This is a trick I figured out for getting a DIV to float exactly in the center of a page. It is really ugly of course, but it works in all browsers.

Dots and Dashes

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

Cleaner

Wow, those five years just flew by, didn't they?

<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
    <table style="position:fixed" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="padding:10px">
                    <img src="Happy.PM.png">
                    <h2>Stays in the Middle</h2>
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

This solution works if the element has width and height

_x000D_
_x000D_
.wrapper {_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  background-color: tomato;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: deepskyblue;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="content"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


You can place the image in a div and add a div id and have the CSS for that div have a text-align:center:

HTML:

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS:

#intro_img {
    text-align: center;
}

The accepted solution of this question didn't work for my case...

I'm doing a caption for some images and I solved it using this:

top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;

display: flex;
align-items: center;

_x000D_
_x000D_
figure {
    position: relative;
    width: 325px;
    display: block
}


figcaption{
    position: absolute;
    background: #FFF;
    width: 120px;
    padding: 20px;

    -webkit-box-shadow: 0 0 30px grey;
    box-shadow: 0 0 30px grey;
    border-radius: 3px;
    display: block;

    top: 0;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;

    display: flex;
    align-items: center;
}
_x000D_
<figure>
    <img  src="https://picsum.photos/325/600">
    <figcaption>
        But as much
    </figcaption>
</figure>
_x000D_
_x000D_
_x000D_


If you need to center horizontally and vertically too:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

.center {
  position: absolute
  left: 50%;
  bottom: 5px;
}

.center:before {
    content: '';
    display: inline-block;
    margin-left: -50%;
}

I understand this question already has a few answers, but I've never found a solution that would work in almost all classes that also makes sense and is elegant, so here's my take after tweaking a bunch:

_x000D_
_x000D_
.container {
    position: relative;
}

.container .cat-link {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%,-50%,0);
    z-index: 100;
    text-transform: uppercase; /* Forces CSS to treat this as text, not a texture, so no more blurry bugs */
    background-color: white;
}

.color-block {
  height: 250px;
  width: 100%;
  background-color: green;
}
_x000D_
<div class="container">
  <a class="cat-link" href="">Category</a>
  <div class="color-block"></div>
</div>
_x000D_
_x000D_
_x000D_

It is saying give me a top: 50% and a left: 50%, then transform (create space) on both the X/Y axis to the -50% value, in a sense "create a mirror space".

As such, this creates an equal space on all the four points of a div, which is always a box (has four sides).

This will:

  1. Work without having to know the parent's height / width.
  2. Work on responsive.
  3. Work on either X or Y axis. Or both, as in my example.
  4. I can't come up with a situation where it doesn't work.

Searching for a solution, I got the previous answers and could make content centered with Matthias Weiler's answer, but using text-align:

#content{
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
}

It worked with Google Chrome and Firefox.


HTML:

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS:

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ddd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

This and more examples here.


Here's a useful jQuery plugin to do this. I found it here. I don't think it's possible purely with CSS.

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
            var el = $(this);
            var h = el.height();
            var w = el.width();
            var w_box = $(window).width();
            var h_box = $(window).height();
            var w_total = (w_box - w)/2; //400
            var h_total = (h_box - h)/2;
            var css = {"position": 'absolute', "left": w_total + "px", "top":
h_total + "px"};
            el.css(css)
    });
};

You can also create the middleware div#centered box centered with absolute, left and right properties and without width property and then set the main content div as its child with display:inline-block box and center it with text-align:center set for its middleware parent box

_x000D_
_x000D_
#container {
  position: relative;
  width: 300px;
  height: 300px;
  border: solid 1px blue;
  color: #DDDDDD;
}

#centered {
  position: absolute;
  text-align: center;
  margin: auto;
  top: 20px;
  left: 0;
  right: 0;
  border: dotted 1px red;
  padding: 10px 0px;
}

#centered>div {
  border: solid 1px red;
  display: inline-block;
  color: black;
}
_x000D_
<div id="container">
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world

  <div id="centered">
    <div>
      hello world <br/>
      I don't know my width<br/>
      but I'm still absolute!
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_


My preferred centering method:

position: absolute;
margin: auto;
width: x%
  • absolute block element positioning
  • margin auto
  • same left/right, top/bottom

A JSFiddle is here.


This works for me:

_x000D_
_x000D_
#content {_x000D_
  position: absolute; _x000D_
  left: 0; _x000D_
  right: 0; _x000D_
  margin-left: auto; _x000D_
  margin-right: auto; _x000D_
  width: 100px; /* Need a specific value to work */_x000D_
}
_x000D_
<body>_x000D_
  <div>_x000D_
    <div id="content">_x000D_
      I'm the content_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_


HTML

<div id='parent'>
  <div id='centered-child'></div>
</div>

CSS

#parent {
  position: relative;
}
#centered-child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto auto;
}

http://jsfiddle.net/f51rptfy/


A simple approach that worked for me to horizontally center a block of unknown width:

<div id="wrapper">
  <div id="block"></div>
</div>

#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

#block {
    display: inline-block;
}

A text-align property may be added to the #block ruleset to align its content independently of the alignment of the block.

This worked on recent versions of Firefox, Chrome, Internet Explorer, Edge and Safari.


I'd like to add on to bobince's answer:

<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>

Improved: /// This makes the horizontal scrollbar not appear with large elements in the centered div.

<body>
    <div style="width:100%; position: absolute; overflow:hidden;">
        <div style="position:fixed; left: 50%;">
            <div style="position: relative; left: -50%; border: dotted red 1px;">
                I am some centered shrink-to-fit content! <br />
                tum te tum
            </div>
        </div>
    </div>
</body>

<div style='position:absolute; left:50%; top:50%; transform: translate(-50%, -50%)'>
    This text is centered.
</div>

This will center all the objects inside div with position type static or relative.


Try not to use the dark side of the CSS. Avoid using negative values for margins. I know that sometimes you are forced to do awful things like a margin-left: -450px, but probably you could do something like right: 450px. It's just my way to work.


Absolute Centre

HTML:

<div class="parent">
  <div class="child">
    <!-- content -->
  </div>
</div>

CSS:

.parent {
  position: relative;
}

.child {
  position: absolute;
  
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  margin: auto;
}

Demo: http://jsbin.com/rexuk/2/

It was tested in Google Chrome, Firefox, and Internet Explorer 8.


This works on any random unknown width of the absolute positioned element you want to have in the centre of your container element:

Demo

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

I have used a similar solution:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

Where "X" is half of the width of a div I want to display. It works fine for me in all browsers.


This is a mix of other answers, which worked for us:

.el {
   position: absolute;
   top: 50%;
   margin: auto;
   transform: translate(-50%, -50%);
}

HTML:

<div id='parent'>
  <div id='child'></div>
</div>

CSS:

#parent {
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}

I know I already provided an answer, and my previous answer, along with others given, work just fine. But I have used this in the past and it works better on certain browsers and in certain situations. So I thought I'd give this answer as well. I did not "Edit" my previous answer and add it because I feel this is an entirely separate answer and the two I have provided are not related.


I just wanted to add if someone wants to do it with a single div tag then here is the way out:

Taking width as 900px.

#styleName {
    position: absolute;
    left: 50%;
    width: 900px;
    margin-left: -450px;
}

In this case one should know the width beforehand.


Sass/Compass version of a previous responsive solution:

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}

#container
{
  position: relative;
  width: 100%;
  float: left
}

#container .item
{
  width: 50%;
  position: absolute;
  margin: auto;
  left: 0;
  right: 0;
}

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to css-position

How does the "position: sticky;" property work? How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? CSS z-index not working (position absolute) Relative div height How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport? How to position the Button exactly in CSS How to make fixed header table inside scrollable div? Absolute positioning ignoring padding of parent Have a fixed position div that needs to scroll if content overflows How to make div fixed after you scroll to that div?

Examples related to center

Center Plot title in ggplot2 How to make a <div> or <a href="#"> to align center How to center an unordered list? Bootstrap 3 modal vertical position center How to align title at center of ActionBar in default theme(Theme.Holo.Light) How to center absolute div horizontally using CSS? Resize to fit image in div, and center horizontally and vertically Center fixed div with dynamic width (CSS) RelativeLayout center vertical Center button under form in bootstrap

Examples related to absolute

React Native absolute positioning horizontal centre How to center div vertically inside of absolutely positioned parent div CSS z-index not working (position absolute) How to center absolute div horizontally using CSS? Set height 100% on absolute div Position: absolute and parent height? How to place a div on the right side with absolute position insert vertical divider line between two nested divs, not full height How to retrieve absolute path given relative Center an element with "absolute" position and undefined width in CSS?