如何使用CSS将一个div置于页面顶部中心位置?

3
我无法将一个div置于页面的顶部中心。我正在使用CSS进行操作,但是没有效果。

#loader {
  position: relative;
  margin: 0 auto;
  text-align: left;
  clear: left;
  height: auto;
  z-index: 0;
}
<body>
  <div id="loader" style='display: none'><img src='img/basic/loader4.gif' /></div>
</body>

我已经花了两个小时,但仍然无法弄清楚。

8个回答

5
首先从id为loader的div中移除"display:none;",并添加"text-align:center;"。
#loader{  
    position:relative;
    margin:0 auto;
    clear:left;
    height:auto;
    z-index: 0;
    text-align:center;/* Add This*/
}​

工作演示: http://jsfiddle.net/surendraVsingh/FCEhD/

2

您需要为div指定特定的宽度,否则它将使用所有可用的宽度,而边距无效。例如:

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

2

如果您想使用margin: 0 auto;,必须指定width属性。



如果您不知道宽度,请添加display: table属性,这样就可以正常工作了。

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

1
在上面的例子中,每个人都认为他想要“全宽度”。
这适用于绝对全宽/高的父容器,但会自动将宽度限制为仅内容宽度。
父容器。
display: block; 
position: absolute;
clear: both;
width: 100%;
height: 100%;
border: solid thin red;

子容器

display: block;
position: absolute;
top:0;
transform: translateX(50%);
padding-left:.5em;
padding-right:.5em;
margin-left:auto;
margin-right:auto;
right:50%;

0
#loader{  
   margin: 0px auto;
   width: 100px;
}

0
#loader
{
    position: absolute;
    width: xxpx;
    height: xxpx;
    margin:0px auto ;

}

或者你可以使用

margin-left:xx;  and `margin-top:0px;`

0

<div id="loader" style='display: none' align="center">

按下ctrl+space,我不确定语法是否正确 在css中,margin和padding都必须设置为0


0
#loader {
    display: none;
    clear: both;
    margin: 0px auto;
    width: [a number] px;
}

当然,你还应该注意浏览器缓存。清除浏览器缓存并重新测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接