html - 固定div的CSS水平居中?
#menu {
position: fixed;
width: 800px;
background: rgb(255, 255, 255); /* The Fallback */
background: rgba(255, 255, 255, 0.8);
margin-top: 30px;
}
我知道这个问题已经有一百万次,但我无法找到解决方案。我有一个div,应该固定在屏幕上,即使页面滚动它应该始终保持在屏幕中间的中心!
div应该有500px宽度,应该是30px远离顶部(margin-top),应该在页面中间水平居中以适应所有浏览器大小,并且在滚动页面的其余部分时不应该移动。
那可能吗?
matt asked 2019-05-01T01:22:28Z
7个解决方案
377 votes
这里的答案已经过时了。 现在,您可以轻松使用CSS3转换而无需编写边距。 这适用于所有元素,包括没有宽度或动态宽度的元素。
水平中心:
left: 50%;
transform: translateX(-50%);
垂直中心:
top: 50%;
transform: translateY(-50%);
水平和垂直:
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
兼容性不是问题:[http://caniuse.com/#feat=transforms2d]
Maciej Krawczyk answered 2019-05-01T01:24:17Z
159 votes
left: 50%;
margin-left: -400px; /* Half of the width */
Quentin answered 2019-05-01T01:22:37Z
54 votes
如果使用内联块是一个选项,我会建议这种方法:
.container {
/* fixed position a zero-height full width container */
position: fixed;
top: 0; /* or whatever position is desired */
left: 0;
right: 0;
height: 0;
/* center all inline content */
text-align: center;
}
.container > div {
/* make the block inline */
display: inline-block;
/* reset container's center alignment */
text-align: left;
}
我在这里写了一篇简短的帖子:[http://salomvary.github.com/position-fixed-horizontally-centered.html]
salomvary answered 2019-05-01T01:25:20Z
23 votes
编辑2016年9月:虽然很高兴仍然偶尔获得投票,因为世界已经转移,我现在选择使用转换的答案(并且有大量的赞成票)。 我不会这样做了。
另一种不必计算保证金或需要子容器的方法:
#menu {
position: fixed; /* Take it out of the flow of the document */
left: 0; /* Left edge at left for now */
right: 0; /* Right edge at right for now, so full width */
top: 30px; /* Move it down from top of window */
width: 500px; /* Give it the desired width */
margin: auto; /* Center it */
max-width: 100%; /* Make it fit window if under 500px */
z-index: 10000; /* Whatever needed to force to front (1 might do) */
}
Nick Rice answered 2019-05-01T01:26:09Z
5 votes
...或者你可以将菜单div换成另一个:
#wrapper{
width:800px;
background: rgba(255, 255, 255, 0.8);
margin:30px auto;
border:1px solid red;
}
#menu{
position:fixed;
border:1px solid green;
width:300px;
height:30px;
}
Meduza answered 2019-05-01T01:26:43Z
5 votes
可以通过这种方式水平居中div:
HTML:
CSS:
.container {
left: 0;
right: 0;
bottom: 0; /* or top: 0, or any needed value */
position: fixed;
z-index: 1000; /* or even higher to prevent guarantee overlapping */
}
.inner {
max-width: 600px; /* just for example */
margin: 0 auto;
}
使用这种方式,您将始终将内部块置于中心位置,此外,它可以很容易地转换为真实的响应(在示例中,它将在较小的屏幕上流动),因此在问题示例和所选答案中没有限制。
Denis V answered 2019-05-01T01:27:54Z
5 votes
这是另一个双重解决方案。 试图保持简洁而不是硬编码。 首先,可预期的html:
content
下面css背后的原理是定位“外部”的某一侧,然后使用它假设“内部”的大小来相对移动后者的事实。
#outer {
position: fixed;
left: 50%; // % of window
}
#inner {
position: relative;
left: -50%; // % of outer (which auto-matches inner width)
}
这种方法与Quentin类似,但内部可以是可变大小的。
Anonymous answered 2019-05-01T01:30:36Z