How to horizontally center an element

4,597,866

Solution 1

You can apply this CSS to the inner <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

Working example here:

#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

EDIT

With flexbox it is very easy to style the div horizontally and vertically centered.

#inner {  
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%;
  display: flex;
  justify-content: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

To align the div vertically centered, use the property align-items: center.

Solution 2

If you don't want to set a fixed width on the inner div you could do something like this:

#outer {
  width: 100%;
  text-align: center;
}

#inner {
  display: inline-block;
}
<div id="outer">  
    <div id="inner">Foo foo</div>
</div>

That makes the inner div into an inline element that can be centered with text-align.

Solution 3

The best approaches are with CSS3.

The old box model (deprecated)

display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.

#outer {
  width: 100%;
  /* Firefox */
  display: -moz-box;
  -moz-box-pack: center;
  -moz-box-align: center;
  /* Safari and Chrome */
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  /* W3C */
  display: box;
  box-pack: center;
  box-align: center;
}

#inner {
  width: 50%;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

According to your usability you may also use the box-orient, box-flex, box-direction properties.

The modern box model with Flexbox

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

Read more about centering the child elements

And this explains why the box model is the best approach:

Solution 4

#centered {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}
<div id="outer" style="width:200px">
  <div id="centered">Foo foo</div>
</div>

Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.

If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.

With CSS calc(), the code can get even simpler:


.centered {
  width: 200px;
  position: absolute;
  left: calc(50% - 100px);
}

The principle is still the same; put the item in the middle and compensate for the width.

Solution 5

I've created this example to show how to vertically and horizontally align.

The code is basically this:

#outer {
 position: relative;
}

and...

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

And it will stay in the center even when you resize your screen.

Share:
4,597,866
Lukas
Author by

Lukas

Updated on May 12, 2022

Comments

  • Lukas
    Lukas about 2 years

    How can I horizontally center a <div> within another <div> using CSS?

    <div id="outer">
      <div id="inner">Foo foo</div>
    </div>
    
    • Jony
      Jony over 6 years
      Of those great answers, I just want to highlight that you must give "#inner" a "width", or it will be "100%", and you can't tell if it's already centered.
    • Akshay K Nair
      Akshay K Nair over 2 years
      display:flex; is the easiest to remember (Chrome gives you guides in DevTools) and supports centering on both axes.
  • Nicolas Guillaume
    Nicolas Guillaume almost 14 years
    For the vertical centering I usually use "line-height" (line-height == height). This is simple and nice but it's only working with a one line content text :)
  • pepkin88
    pepkin88 over 13 years
    in some cases writing !important clause for margin style of inner div would be necessary, e.g. when you wrote something like this outer div {margin: 0.5em;}
  • gman
    gman almost 13 years
    and if you don't know the width? Say because the content is dynamic?
  • Fabio
    Fabio over 12 years
    You have to use the !DOCTYPE tag on your html page to make it work well on IE.
  • Zhanger
    Zhanger almost 11 years
    can someone explain how display:table works? why do elements with this styling applied automatically shrink to the size of the inner elements
  • kongaraju
    kongaraju over 10 years
    what do you mean by "syntax is outdated", is it deprecated?
  • Mert Mertce
    Mert Mertce over 10 years
    Note that it may be necessary to add "float:none;" for the #inner.
  • cimmanon
    cimmanon over 10 years
    The Flexbox specification has gone through 3 major revisions. The most recent draft is from Sept 2012, which officially deprecates all previous drafts. However, browser support is spotty (particularly old Android browsers): stackoverflow.com/questions/15662578/…
  • Lalit Kumar Maurya
    Lalit Kumar Maurya over 10 years
    text-align work for text alignment in its container not for its container to its parent.
  • Pnsadeghy
    Pnsadeghy over 10 years
    i test it , i problem with set child to center , must when you have more one child , more times margin:0 auto font answer , but , text-align center , for parent make this child be center , even if they are element and not be text , test and see what happen
  • Lalit Kumar Maurya
    Lalit Kumar Maurya over 10 years
    text-align center text only. You right at this time but when you write a container css which contains a child with different width and color your code does't work. Test it again!!!!
  • Lalit Kumar Maurya
    Lalit Kumar Maurya over 10 years
    See this example jsfiddle.net/uCdPK/2 and tell me what do you think about it!!!!!
  • stvnrynlds
    stvnrynlds over 10 years
    +1 for this method, I was about to answer with it. Note that you must declare a width on the element you wish to center horizontally (or height if centering vertically). Here's a comprehensive explanation: codepen.io/shshaw/full/gEiDt. One of the more versatile and widely-supported methods of centering elements vertically and/or horizontally.
  • DaveWalley
    DaveWalley over 10 years
    This worked for me and am not sure why it isn't the answer. Can someone explain what is wrong with this?
  • SpYk3HH
    SpYk3HH over 10 years
    @Zhanger FYI: <div style="display: table;">stuff</div> is the same as <table>stuff</table>. Assigning the display that way just tells the browser to render the element as a table.
  • Idra
    Idra over 10 years
    @DaveWalley though works there are 2 good reasons why this is not a good answer. 1st the question was for a CSS solution and this is a pure HTML solution. 2nd the CENTER tag was already deprecated in HTML 4
  • Emmanuel Touzery
    Emmanuel Touzery over 10 years
    You also set the top and bottom margins to 0, which is unrelated. Better putting margin-left: auto; margin-right: auto I think.
  • Gui Imamura
    Gui Imamura about 10 years
    Yes, I believe this is a duplicate. The top answer by Justin Poliey has solved the problem in the same way.
  • rybo111
    rybo111 about 10 years
    To support mobile browsers, I do not recommend using width: 50%. Use something like max-width: 300px instead.
  • Sam Su
    Sam Su almost 10 years
    This works fine on Chrome but does NOT support mobile browsers like Safari.
  • Squirrl
    Squirrl almost 10 years
    You cannot use padding within the div, but if you want to give the illusion use a border of the same color.
  • Michael Terry
    Michael Terry over 9 years
    As your fiddle notes, #inner has to have a width set on it.
  • Michael Terry
    Michael Terry over 9 years
    That centers it vertically.
  • clickbait
    clickbait almost 9 years
    That's not centering the div, that's centering the text.
  • Joe Hansen
    Joe Hansen almost 9 years
    Safari, as of now, still requires -webkit flags for flexbox (display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center;)
  • Skippy le Grand Gourou
    Skippy le Grand Gourou over 8 years
    One may need vendor prefixes as well : -webkit-transform: translate(-50%,0); -moz-transform: translate(-50%,0); -ms-transform: translate(-50%,0); -khtml-transform: translate(-50%,0); -o-transform: translate(-50%,0);
  • Rapnar
    Rapnar over 8 years
    Thnx for trying to help the OP :). You shouldn't add answers that are exactly the same as answers already provided. I'm guessing the collision is a mistake but this could have been completely copied and pasted from the accepted answer.
  • Doug McLean
    Doug McLean over 8 years
    @SabaAhang the correct syntax for that would be float: none; and is probably only needed because #inner has inherited a float of either left or right from somewhere else in your CSS.
  • Jose Rui Santos
    Jose Rui Santos over 8 years
    Just set this rule for #inner only: #inner { position:relative; left:50%; transform:translateX(-50%); }. This works for any width.
  • Aloso
    Aloso over 8 years
    I don't like this solution because when the inner element is too broad for the screen, you can't scroll over the whole element horizontally. margin: 0 auto works better.
  • sarath
    sarath over 8 years
    CSS margin:0 auto will not work when the div has position property other than relative, like in the case of position:absolute
  • YakovL
    YakovL about 8 years
    Not necessarily margin:0 auto: it can be margin: <whatever_vertical_margin_you_need> auto second being the horizontal margin.
  • Billal Begueradj
    Billal Begueradj over 7 years
    This is far from being a perfect solution as anything inside the inner DIV must be displayed as a table's element
  • pmoleri
    pmoleri over 7 years
    This is a nice solution. Just keep in mind that inner will inherit text-align so you may want to set inner's text-align to initial or some other value.
  • amit bende
    amit bende over 7 years
    only add text-align center in your perent div (outer) so their children class take that css autometicaly
  • try-catch-finally
    try-catch-finally over 7 years
    Please add some explanation what technologies you're using and how it's working. A reference link would be fine.
  • Eiko
    Eiko over 7 years
    How is this different to the many other answers that seem to do the same?
  • Wouter Vanherck
    Wouter Vanherck about 7 years
    Isn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment?
  • Danield
    Danield about 7 years
    @WouterVanherck it depends on the flex-direction value. If it is 'row' (the default) - then justify-content: center; is for the horizontal alignment (like I mentioned in the answer) If it is 'column' - then justify-content: center; is for the vertical alignment.
  • amachree tamunoemi
    amachree tamunoemi about 7 years
    voted most but not a better solution. the best way to do this is to use the combination of div and span tag, block css property and cross browser inline-block, and text center will do the simple magin
  • Garric
    Garric almost 7 years
    The <center> tag is deprecated since HTML4, like Idra explained in comments
  • Heitor
    Heitor almost 7 years
    @Garric15 I'm just trying to encourage some ppl who maybe keep losing hours and hours of work for solving a very tiny problem just because they don't want to use a deprecated tag like <center> despite it keeps working perfectly fine in some cases. The <center> tag was deprecated but nothing as simple and effective as it came to replace it decently in all cases.
  • Saurabh Tiwari
    Saurabh Tiwari almost 7 years
    Why this doesn't work if inner element is button and not a div.
  • Matt Cremeens
    Matt Cremeens almost 7 years
    I used this, too, but I've never encountered display: table; before. What does it do?
  • Simon Logic
    Simon Logic almost 7 years
    Because "input" is inline element and must be centered by "text-align: center".
  • Ian H.
    Ian H. over 6 years
    Thank you for your answer! If you think that your answer contributes something valuable to the question, be sure to further explain your code and what it does and why it works, thanks!
  • livefreeor
    livefreeor over 6 years
    this worked for me. most of the time display block then margin auto for inner div doesnt work but with the display flex in outer div worked great. thanks alot. I havent tried the display flex before.
  • antelove
    antelove over 6 years
    me too. using display table also great. my another answer. stackoverflow.com/questions/5703552/…
  • heytools
    heytools over 6 years
    text-align is actually necessary for it to work in IE quicks mode, so if you don't mind adding a little expression to support older browsers keep it there. (IE8 with IE8 rules and IE7 rules both work without text-align, so may be it's only IE6 and older that are concerned)
  • bananaforscale
    bananaforscale over 6 years
    margin-left: auto; margin-right: auto; centres a block level element
  • bananaforscale
    bananaforscale over 6 years
    The default width for most block level elements is auto, which fills the available area on screen. Just being centered places it in the same position as left alignment. If you wish it to be visually centered you should set a width (or a max-width although Internet Explorer 6 and earlier do not support this, and IE 7 only supports it in standards mode).
  • BlackBeard
    BlackBeard over 6 years
    Please add some explanations as well.
  • Anu
    Anu over 6 years
    <div class="DivCenter"></div>
  • iBug
    iBug over 6 years
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
  • Peter Mortensen
    Peter Mortensen about 6 years
    The second link seems to be (effectively) broken.
  • Admin
    Admin about 6 years
    max-width? what about that?
  • NoChance
    NoChance almost 6 years
    This may not work if you have other divs below the centered div.
  • Mobarak Ali
    Mobarak Ali about 5 years
    #outer doesn't need any width:100%; as the <div> by default always has width:100%. and text-align:center is also not a necessary at all.
  • Javed Khan
    Javed Khan almost 5 years
    use above css for center align div
  • d_kennetz
    d_kennetz almost 5 years
    Hi! This answer came up in review as low quality because of its length and content. This happens because code only answers are generally discouraged on SO and should be accompanied by some text explanation of how the code is a solution to the question. Thanks!
  • Matthew Kerian
    Matthew Kerian almost 5 years
    Please put some text showing what you did and why you did it
  • Rick
    Rick over 4 years
    I use width: fit-content; and margin: 0 auto. I think this can work with unknown width.
  • simon
    simon over 4 years
    @amachreetamunoemi do you think that? then could you ask with a better solution
  • simon
    simon over 4 years
    I always think that use lots code is bad practice for example with this code I center my div: display: table; margin: auto; simple and easy
  • Peter Mortensen
    Peter Mortensen over 4 years
    Re "width 100%;": Do you mean "width: 100%;"?
  • Peter Mortensen
    Peter Mortensen over 4 years
  • Shoma
    Shoma about 4 years
    if you look into jsfiddle.net/jinny/p3x5jb81/9 , i just added border to show that in my case centered div is not 100%, it takes size/length of the text content. If centered text has content length bigger than the outer div than I agree we need to give inner div a width. But my solution support the given sample case.
  • Peter Mortensen
    Peter Mortensen about 4 years
    An explanation would be in order.
  • Peter Mortensen
    Peter Mortensen about 4 years
    An explanation would be in order.
  • Peter Mortensen
    Peter Mortensen about 4 years
    An explanation would be in order.
  • Thielicious
    Thielicious almost 4 years
    <center> is only a predefined tag, not adjustable, not flexible as in CSS. It still works but those are one of the last living remnants just like <blink> and <font>. Deprecated doesn't mean that it will no more work in future... it also means that new techonolgies, be it via node react using JSX or other complex MVCs that generate virtual DOMs might be not fully capable to work with. That they still work in HTML5 despite not supported means that w3c no longer maintains it. Also SEO: Websites with deprecated HTML may signalize search engines with outdated code which could harm your ranking.
  • CodeToLife
    CodeToLife almost 4 years
    in regards to edit records this person answered first on the page. Upvoting.
  • Phani Rithvij
    Phani Rithvij almost 4 years
    This is the only one that works for perfect centering and will remain centered even after the contents in the div are modified.
  • konekoya
    konekoya over 3 years
    Just learned this today. And people should use this instead of some other hacky ways to solve the centering issue. For people who want to learn more about this, check out web.dev/one-line-layouts
  • M.Idrish
    M.Idrish over 3 years
    display: flex; justify-content: center; this work perfect
  • Felypp Oliveira
    Felypp Oliveira over 3 years
    It's a nice trick, but there is a little caveat. If the element has inline content that's wider than 50% of the parent's width, then the extra 50% offset from the left will extrapolate the parent's width, breaking the content to the next lines to avoid overflow. But it's possible to keep the content inline by setting in the centered element the white-space attribute to nowrap. Try that in this JSFiddle.
  • user3481644
    user3481644 over 2 years
    This is perfect ... I had to add "position: unset" because of an inherited attribute, but otherwise, perfect!
  • dkellner
    dkellner almost 2 years
    It's now replaced by flexbox so it's not recommended anymore - still, worth an upvote for me!