div 是 50% 不透明的,显示在网站内容的顶部,固定宽度为 960 像素(由 jQuery 创建)。
如何水平居中?
margin: 0 auto;
不起作用:(
最佳答案
margin: 0 auto;
不适用于绝对定位的元素。相反,我们可以使用元素本身的属性。检查 fiddle ...
http://jsfiddle.net/UnsungHero97/HnzyT/2/
将它水平居中很容易,因为您绝对知道宽度和它的位置。您所要做的就是给它 2 个 CSS 属性:
width: 960px;
position: absolute;
/* ... other CSS properties... */
left: 50%; /* 1. move it to the right 50% of the width of the page; now the left side of the element is exactly in the middle */
margin-left: -480px; /* move the element to the left exactly half of its width and now the center of the element is centered horizontally */
如果您希望它在垂直和水平方向上都居中,您需要知道该元素的和有多宽。
希望对您有所帮助。
赫里斯托
关于javascript - css/jQuery - 居中绝对定位的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5811957/