css - 从顶部的绝对位置,水平居中的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5967758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
css - absolute position from top, horizontally centered div
提问by captainandcoke
I've looked at a googol google results without finding any that work.
我查看了 googol google 结果,但没有找到任何工作。
I need to have my div (height 333 px, width 550 px) to be centered horizontally and always be 275 px from the top. Every time I try to do this it just disappears.
我需要让我的 div(高度 333 像素,宽度 550 像素)水平居中,并且始终距顶部 275 像素。每次我尝试这样做时,它都会消失。
回答by fuxia
If the div should sit on top you have to use position:absolute
. Otherwise, the answer from @sdleihssirhc should work.
如果 div 应该位于顶部,则必须使用position:absolute
. 否则,@sdleihssirhc 的答案应该有效。
Example with positioning
定位示例
#middlebox
{
position: absolute;
top: 275px;
left: 50%; /* move the left edge to the center … */
margin-left: -275px; /* … and move it to the left half the box' width. */
z-index: 9999; /* Try to get it on top. */
}
Use tools like Dragonflyor Firebugto inspect the properties if it still disappears.
回答by sdleihssirhc
Depending on the content and context, you could just set that div's margin:
根据内容和上下文,您可以设置该 div 的边距:
margin: 275px auto 0;
回答by Jimmy
Unless you're thinking of static positioning, I don't think that you would need to use absolute positioning at all. Try this:
除非您考虑静态定位,否则我认为您根本不需要使用绝对定位。尝试这个:
<html>
<head>
<title>Test</title>
</head>
<body>
<div style="width:550px; height:333px; background-color:orange; margin: 275px auto">
Is this what you want?
</div>
</body>
</html>