문제

Any ideas why the footer is not centering in the following code?

<html>
    <head>
        <style>
            #container {width:1000px;margin:0 auto;}
            #footer {margin:0 auto;}
        </style>
    </head>
    <body>
        <div id="container">

            <div>
                lksdfkjjindskfjsfkjflskfjsls.....sdlfkajsf
                sdfkjkkdiidkdkn   asdflkajf;lskdfioasfnasldf  ;lkjlthis is just a testing  
                ' sdlfk  sdlfk  dslfkjsf lskdfjsaf this elobrate   asdfkj   
                sdlfk  sldkfjsodsf lsdkfj   dlkjhgkjhgkjhg
            </div>

            <div id="footer">
                copyright 2014
            </div>

        </div>
    </body>
</html>

http://jsfiddle.net/WJw5H/

도움이 되었습니까?

해결책

By default a div is a block element. This means it has width: 100%;. margin: 0 auto; will center the element but how can it do that if its width: 100%.

For that matter!

Actually it has width: auto, which for a block-level element is the full width of its container - but that's not 100% because otherwise padding would make it overflow - Niet the Dark Absol

DEMO HERE

CSS:

#footer { width: 200px; margin:0 auto;}

Also you could just text-align: center;

DEMO HERE

다른 팁

Setting a width would resolve, but you would have to calculate the exact width for it, and when the footer changes, you will need to recalculate and update the width property as well.

A nice solution to that would be setting the display to table, so the width issue will automatically be resolved:

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

See fiddle here

#footer { text-align: center;  

   margin-left: auto ;
  margin-right: auto ;

}

try this it will work perfect

copy this to the demo on http://jsfiddle.net/WJw5H/15/

<div id="container">

this is just a test.
</div>
<div id="footer">

copyright 2014

</div>

#container {width:1000px;margin:0 auto;}
#footer { text-align: center;  

   margin-left: auto ;
  margin-right: auto ;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top