0

是的,对此还有其他问题;但我无法按照他们的指示制作这个 div 中心。为什么?

HTML

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css">
    </head>
    <body>
        <div>
            <div class="center"></div>
        </div>
    </body>
</html>

CSS:

body {
    line-height: 1;
}

.center {
    position: fixed;
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 300px;
}
4

7 回答 7

2

Change the position:fixed; to position:relative;

于 2013-06-12T23:38:54.047 回答
1

Remove the position: fixed from the divs style.

Also, you don't need the display: block... it should default to that anyway. And poke is correct, you shouldn't need that extra div.

Here's an example of it working... http://jsfiddle.net/VYmw6/1/

于 2013-06-12T23:39:12.533 回答
1

Your div won't get centered because you've got position:fixed, if you remove that it will work. :)

See JSfiddle here: http://jsfiddle.net/6XWMR/

于 2013-06-12T23:39:21.993 回答
1

The position: fixed makes the div position itself absolutely (and fixed, making it stay where it is when you scroll). This means that auto-margin won’t work. You can either fix this by removing the position rule, or by positioning the div absolutely instead:

.center {
    position: fixed;
    width: 300px;
    left: 50%;
    margin-left: -150px;
}

On an unrelated note, the additional div is completely useless, you can just leave that out. Also, divs are block elements by default, so you can leave out the display: block; rule as well.

于 2013-06-12T23:40:51.650 回答
1

用它 !

.center {

margin-left: auto;
margin-right: auto;
width: 300px;
 }

or

.center {

margin:0 auto; 
width: 300px;
 }

这是小提琴

于 2013-06-13T07:57:59.240 回答
1

你有什么理由使用position: fixed吗?但无论如何希望这对你有帮助

CSS:

.center {
    margin: 0 auto;
    width: 300px;
}

演示

于 2013-06-13T00:28:20.320 回答
-1

将您的代码更改为

<center>
     <div> 
          content
     </div>
</center>

基本上,将要在标签内居中的 div 括起来。

希望这对您的项目有所帮助并一切顺利:-)

于 2013-06-13T07:45:03.893 回答