質問

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