1578

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

I tried the following CSS code, but it needs to be adjusted because the width is responsive.

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

How can I achieve this?

1

39 Answers 39

2300

This works for me:

#content {
  position: absolute; 
  left: 0; 
  right: 0; 
  margin-inline: auto; 
  width: fit-content;
}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>

30
  • 61
    I just want to get across that negative margins are perfectly valid CSS and should not be viewed as a "dirty hack". Negative margins are mentioned in the W3C box model specification. Some individuals seem to arbitrarily decide it is a hack because they a) are ignorant to them, or b) are using them to fix their bad CSS. Commented Aug 16, 2012 at 1:33
  • 72
    the width of the div to be centered has to be set - won't work automagically with, say, a button with text on it.
    – Stefan
    Commented Jan 27, 2013 at 11:12
  • 3
    @Joshua This will only center horizontally, not vertically like the other answer.
    – ygoe
    Commented Jan 31, 2013 at 19:22
  • 4
    I prefer this solution as it doesn't increase the viewport size.
    – iceydee
    Commented Mar 4, 2013 at 11:39
  • 18
    For cross-browser support: width should be set to a specific value for this to work. auto and 100% will not center the element. display: block; is a must. position: absolute; is NOT a must. All values will work. Parent element's position should be set to something other than static. Setting left and right to 0 is unnecessary. margin-left: auto; margin-right: auto; will do the work. Commented Jun 27, 2014 at 16:12
1533

<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>

5
  • 86
    Awesome. Worked for me! One problem I had: The image I was centering was quite big, this caused the outer div to go beyond the right edge of the page and cause horizontal scrolling. I swapped out the "left" css property for "right", and so far it works better since going over the left edge of the screen doesnt cause scrolling
    – BoomShaka
    Commented Oct 26, 2011 at 10:28
  • what if user has scrolled the page down, overylay appears on the top, do you think it will be a good idea to use jquery to fix scroll issue
    – PUG
    Commented Sep 1, 2012 at 5:45
  • 2
    one solution for scroll issue can be position: fixed but what if height is unknown of overlay, scroll bars for overlay will have to be implemented
    – PUG
    Commented Sep 1, 2012 at 5:49
  • Solution for scrolling can be this, did not test it enough though, wht do you guys think of this solution? var scrolled =$(window).scrollTop(); if(scrolled>0) { var offset = $('#containerOverlay').offset(); $('#containerOverlay').css('top',($(window).height() * 0.05) + scrolled); }
    – PUG
    Commented Sep 1, 2012 at 6:39
  • The problem with this is that it causes text to be broken at 50% of the viewport's width, because the wrapper div can only take up 50% of the viewport starting in the middle. If you want the text to break at 100% viewport width this isn't gonna work.
    – Jez
    Commented Nov 11, 2022 at 16:19
1399

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);
}

.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;
}
<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>

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%);

32
  • 46
    With IE7 support no longer necessary, this should be the de facto solution. This solution is better than the left:0/right:0 technique since that makes the elements full width while this retains the width and works on elements of unknown widths.
    – aleemb
    Commented Nov 21, 2014 at 6:09
  • 69
    By far the best answer, this works if the box the div is contained in is smaller than the child.
    – Case
    Commented Nov 23, 2014 at 13:14
  • 2
    @ChadJohnson of course it does. Try it with the webkit- prefix as I suggested. Commented Feb 12, 2015 at 9:59
  • 3
    transform: translate seems to make position: fixed unusable in children. The accepted answer works better in this case.
    – dmvianna
    Commented Apr 1, 2015 at 4:44
  • 1
    Is the accepted answer the recommended workaround, or can you point me in the right direction?
    – dmvianna
    Commented Apr 1, 2015 at 7:42
120

<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.

3
  • Re "059%": Do you mean "50%"? If so, please respond by editing your answer, not here in comments. Commented Jun 20, 2020 at 10:31
  • I have a slightly different case and I'm very glad about your hint to transform: translate()!
    – BergListe
    Commented Nov 16, 2020 at 11:19
  • We should limit the usage of transform because this is conflicting with animations.
    – Loenix
    Commented Oct 21, 2021 at 15:54
55

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:

.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;
}
<div class="container">
    <div class="center"></div>
</div>

I found it very helpful.

0
50

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.

3
  • 33
    "because the width is unknown" ... this doesn't answer the question Commented Oct 3, 2013 at 13:20
  • 15
    hi @Michel actually when you google search for something related to centering the absolute div, this link comes as the first link. That's why I added this solution, in case someone like me is in search for the above solution.. :)
    – pratikabu
    Commented Oct 23, 2013 at 13:08
  • 1
    Not very useful for responsive design, but it worked for me until I started doing responsive designs. This is a valid answer for centering absolutely positioned known width elements. Commented Mar 19, 2014 at 20:30
39

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.

3
  • This doesn't work, please check the following codepen codepen.io/anon/pen/YqWxjJ
    – Mark
    Commented Mar 11, 2016 at 3:20
  • 1
    Sorry I think this will work but you need to include a fixed height and width codepen.io/anon/pen/WwxEYQ
    – Mark
    Commented Mar 11, 2016 at 3:36
  • I don't understand why setting left and right to 0 means in this context when it's used with margin auto. Care to explain?
    – Robert
    Commented May 16, 2021 at 15:24
37

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

3
  • 2
    I think you need to add height for vertical to work.
    – Raul
    Commented Dec 27, 2014 at 19:18
  • Looks like this positions in the center of the page, not the center of another element. Commented Nov 18, 2015 at 17:31
  • 1
    @GünterZöchbauer yes, if you want make element center of parent, set position of parent relative. Commented Nov 19, 2015 at 6:53
29

If you need to center horizontally and vertically too:

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

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.

3
  • 6
    I think you don't need the "text-align: center"
    – Tobias
    Commented Aug 6, 2013 at 9:00
  • 1
    I needed the "text-align: center", and this worked where the solution suggested by @ProblemsOfSumit didn't work as it made my text wrap.
    – Nat
    Commented Dec 13, 2018 at 12:56
  • Now, this is brilliant.
    – Chimdi
    Commented Jul 20 at 9:37
17

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:

.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;
}
<div class="container">
  <a class="cat-link" href="">Category</a>
  <div class="color-block"></div>
</div>

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.
3
  • Please do let me know if you find a situation where this doesn't work so I could edit the question with your input. Commented Nov 26, 2017 at 18:28
  • transform / translate will causes safari to render text blurred on certain scale
    – James Tan
    Commented Jan 9, 2018 at 9:02
  • @DanielMoss any reason to not use translate(-50%,-50%);? Commented Aug 3, 2018 at 9:40
17

Flexbox can be used to center an absolute positioned div.

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

.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);
}
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>

3
  • on my screen -Firefox 68.x, it just doesn't align, the absolute block appears at the bottom of the relative block
    – DiaJos
    Commented Mar 17, 2020 at 21:45
  • Can you try this display: -webkit-flex;? Commented Mar 17, 2020 at 23:27
  • 2
    It'll not work for absolute positioned items
    – Md. A. Apu
    Commented Apr 20, 2021 at 10:59
17

It's possible to center an element that has aspect-ratio:1 with position absolute by using calc()

In the following example I'm using a circle because it's easier to explain and understand, but the same concept can be applied to any shape with aspect-ratio:1 meaning that the width and height are equal. (about aspect-ratio)

:root{
  --diameter: 80px;
}
div{
  position:absolute;
  top: calc(50% - var(--diameter)/2);
  right:calc(50% - var(--diameter)/2);
  aspect-ratio:1;
  width:var(--diameter);
  border-radius:100%;
  background:blue;
}
<div/>

Explanation

enter image description here

4
  • 5
    This only applies for elements of knows size Commented Dec 2, 2022 at 13:43
  • @RokoC.Buljan what do you mean ? can you expand on that ?
    – Gass
    Commented Dec 2, 2022 at 14:07
  • They meant that ø or --diameter should be know in order for this method to work. Sometimes we work with elements with auto/fit-content dimensions
    – Vega
    Commented Jan 10 at 9:40
  • @Vega well, yes.. this doesn't apply to all cases. ø is a variable, meaning it can be any value and it will work okay, only if the aspect-ratio equals 1. I was having fun doing this and I didn't intend it to work for all cases.
    – Gass
    Commented Jan 10 at 13:27
16

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

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

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;
}
10

This worked for me:

.container{
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}
<div class="container"><p>My text</p></div>

2
  • 1
    It's @Matthias Weiler answer 5 years later.
    – aloisdg
    Commented Nov 19, 2016 at 9:43
  • 1
    Even after fixing the typo, this doesn't even work as answered. On top of trying to copy Matthias Weiler's solution.
    – TylerH
    Commented Nov 28, 2023 at 20:45
7

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.

2
  • +1 for the "margin: auto" thing. I've tried this before to horizontally centre a div using the line "margin: 0 auto" - the "0" applying to the vertical margins and the "auto" the horizontal. I think this is what StackOverflow uses for the very top level div to get the 2 thick white borders down the sides of the page. However, the W3Schools page on CSS margin states for the auto value that "The result of this is dependant of the browser" - I've not personally tried it across many different browsers, so I can't really comment on this point (but it obviously does the trick in some of them)
    – Steg
    Commented Nov 21, 2009 at 22:23
  • 1
    it is possible for an unknown width (and height) if IE8 isn't an issue. See my answer for details. Commented Sep 8, 2014 at 16:35
7

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>
7

Just wrap your content with a new div and use display flex and then use align-items: center; and justify-content: center; take a look...

<div class="firstPageContainer">
  <div class="firstPageContainer__center"></div>
</div>
.firstPageContainer{
  display: flex;
  width: 1000px;
  height: 1000px;
  justify-content: center;
  align-items: center;
  background-color: #FF8527;
}

.firstPageContainer__center{
  position:absolute;
  width: 50px;
  height: 50px;
  background-color: #3A4147;
}
5

Sass/Compass version of a previous responsive solution:

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}
2
  • 5
    transform: translate(-50%, -50%) makes text and all other content blurry on OS X using webkit browsers. keithclark.co.uk/articles/gpu-text-rendering-in-webkit
    – Yasha
    Commented Dec 15, 2015 at 20:21
  • Just use the type of antialiasing that you like -webkit-font-smoothing: antialiased; I've gleaned that from the article you posted btw! Commented Dec 22, 2015 at 7:22
4

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.

3

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)
    });
};
4
  • this is the better way, and especially with repsonsive design.
    – m4tm4t
    Commented Oct 18, 2012 at 10:58
  • Would be trivial if jQuery was used in any case Commented Jan 13, 2014 at 15:27
  • 9
    this is NOT the better way. It's always better to use CSS whenever possible. Centering a DIV is possible with CSS in every axis and also for responsive pages. There is no need for JavaScript! Commented Apr 30, 2014 at 9:25
  • 1
    @yckart and in this case the tool is CSS. Commented Apr 28, 2015 at 7:21
3
#container
{
  position: relative;
  width: 100%;
  float: left
}

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

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.

3

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;

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;
}
<figure>
    <img  src="https://picsum.photos/325/600">
    <figcaption>
        But as much
    </figcaption>
</figure>

2

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/

2

If you're using TailwindCSS - It's 2024!

Based on the top trending answer: https://stackoverflow.com/a/23384995/687549

<div className="relative">
   <div className="absolute left-1/2 -translate-x-1/2">I AM CENTERED</div>
</div>
1

This solution works if the element has width and height

.wrapper {
  width: 300px;
  height: 200px;
  background-color: tomato;
  position: relative;
}

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

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

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

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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.