How to horizontally center an element
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.
Lukas
Updated on May 12, 2022Comments
-
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 over 6 yearsOf 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 over 2 years
display:flex;
is the easiest to remember (Chrome gives you guides in DevTools) and supports centering on both axes.
-
-
Nicolas Guillaume almost 14 yearsFor 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 over 13 yearsin some cases writing
!important
clause for margin style of inner div would be necessary, e.g. when you wrote something like thisouter div {margin: 0.5em;}
-
gman almost 13 yearsand if you don't know the width? Say because the content is dynamic?
-
Fabio over 12 yearsYou have to use the !DOCTYPE tag on your html page to make it work well on IE.
-
Zhanger almost 11 yearscan someone explain how display:table works? why do elements with this styling applied automatically shrink to the size of the inner elements
-
kongaraju over 10 yearswhat do you mean by "syntax is outdated", is it deprecated?
-
Mert Mertce over 10 yearsNote that it may be necessary to add "float:none;" for the #inner.
-
cimmanon over 10 yearsThe 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 over 10 yearstext-align work for text alignment in its container not for its container to its parent.
-
Pnsadeghy over 10 yearsi 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 over 10 yearstext-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 over 10 yearsSee this example jsfiddle.net/uCdPK/2 and tell me what do you think about it!!!!!
-
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 over 10 yearsThis worked for me and am not sure why it isn't the answer. Can someone explain what is wrong with this?
-
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 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 over 10 yearsYou also set the top and bottom margins to 0, which is unrelated. Better putting
margin-left: auto; margin-right: auto
I think. -
Gui Imamura about 10 yearsYes, I believe this is a duplicate. The top answer by Justin Poliey has solved the problem in the same way.
-
rybo111 about 10 yearsTo support mobile browsers, I do not recommend using
width: 50%
. Use something likemax-width: 300px
instead. -
Sam Su almost 10 yearsThis works fine on Chrome but does NOT support mobile browsers like Safari.
-
Squirrl almost 10 yearsYou cannot use padding within the div, but if you want to give the illusion use a border of the same color.
-
Michael Terry over 9 yearsAs your fiddle notes, #inner has to have a width set on it.
-
Michael Terry over 9 yearsThat centers it vertically.
-
clickbait almost 9 yearsThat's not centering the div, that's centering the text.
-
Joe Hansen almost 9 yearsSafari, 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 over 8 yearsOne 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 over 8 yearsThnx 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 over 8 years@SabaAhang the correct syntax for that would be
float: none;
and is probably only needed because #inner has inherited afloat
of eitherleft
orright
from somewhere else in your CSS. -
Jose Rui Santos over 8 yearsJust set this rule for
#inner
only:#inner { position:relative; left:50%; transform:translateX(-50%); }
. This works for any width. -
Aloso over 8 yearsI 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 over 8 yearsCSS
margin:0 auto
will not work when the div hasposition
property other thanrelative
, like in the case ofposition:absolute
-
YakovL about 8 yearsNot necessarily
margin:0 auto
: it can bemargin: <whatever_vertical_margin_you_need> auto
second being the horizontal margin. -
Billal Begueradj over 7 yearsThis is far from being a perfect solution as anything inside the inner DIV must be displayed as a table's element
-
pmoleri over 7 yearsThis is a nice solution. Just keep in mind that inner will inherit
text-align
so you may want to set inner'stext-align
toinitial
or some other value. -
amit bende over 7 yearsonly add text-align center in your perent div (outer) so their children class take that css autometicaly
-
try-catch-finally over 7 yearsPlease add some explanation what technologies you're using and how it's working. A reference link would be fine.
-
Eiko over 7 yearsHow is this different to the many other answers that seem to do the same?
-
Wouter Vanherck about 7 yearsIsn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment?
-
Danield about 7 years@WouterVanherck it depends on the
flex-direction
value. If it is 'row' (the default) - thenjustify-content: center;
is for the horizontal alignment (like I mentioned in the answer) If it is 'column' - thenjustify-content: center;
is for the vertical alignment. -
amachree tamunoemi about 7 yearsvoted 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 almost 7 yearsThe
<center>
tag is deprecated since HTML4, like Idra explained in comments -
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 almost 7 yearsWhy this doesn't work if inner element is
button
and not adiv
. -
Matt Cremeens almost 7 yearsI used this, too, but I've never encountered
display: table;
before. What does it do? -
Simon Logic almost 7 yearsBecause "input" is inline element and must be centered by "text-align: center".
-
Ian H. over 6 yearsThank 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 over 6 yearsthis 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 over 6 yearsme too. using display table also great. my another answer. stackoverflow.com/questions/5703552/…
-
heytools over 6 yearstext-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 over 6 yearsmargin-left: auto; margin-right: auto; centres a block level element
-
bananaforscale over 6 yearsThe 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 over 6 yearsPlease add some explanations as well.
-
Anu over 6 years<div class="DivCenter"></div>
-
iBug over 6 yearsThank 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 about 6 yearsThe second link seems to be (effectively) broken.
-
Admin about 6 yearsmax-width? what about that?
-
NoChance almost 6 yearsThis may not work if you have other divs below the centered div.
-
Mobarak Ali about 5 years
#outer
doesn't need anywidth:100%;
as the<div>
by default always haswidth:100%
. andtext-align:center
is also not a necessary at all. -
Javed Khan almost 5 yearsuse above css for center align div
-
d_kennetz almost 5 yearsHi! 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 almost 5 yearsPlease put some text showing what you did and why you did it
-
Rick over 4 yearsI use
width: fit-content;
andmargin: 0 auto
. I think this can work with unknown width. -
simon over 4 years@amachreetamunoemi do you think that? then could you ask with a better solution
-
simon over 4 yearsI 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 over 4 yearsRe "
width 100%;
": Do you mean "width: 100%;
"? -
Peter Mortensen over 4 years
-
Shoma about 4 yearsif 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 about 4 yearsAn explanation would be in order.
-
Peter Mortensen about 4 yearsAn explanation would be in order.
-
Peter Mortensen about 4 yearsAn explanation would be in order.
-
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 almost 4 yearsin regards to edit records this person answered first on the page. Upvoting.
-
Phani Rithvij almost 4 yearsThis is the only one that works for perfect centering and will remain centered even after the contents in the div are modified.
-
konekoya over 3 yearsJust 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 over 3 yearsdisplay: flex; justify-content: center; this work perfect
-
Felypp Oliveira over 3 yearsIt'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 thewhite-space
attribute tonowrap
. Try that in this JSFiddle. -
user3481644 over 2 yearsThis is perfect ... I had to add "position: unset" because of an inherited attribute, but otherwise, perfect!
-
dkellner almost 2 yearsIt's now replaced by flexbox so it's not recommended anymore - still, worth an upvote for me!