CSS/jQuery - 居中绝对定位的 div

10
的不透明度为 50%,它显示在网站内容的上方,且其宽度固定为 960 像素(由 jQuery 创建)。
怎样使其水平居中呢?
margin: 0 auto; 无效 :(
2个回答

23

margin: 0 auto; 对于绝对定位的元素无效。相反,我们可以通过改变元素本身的属性来进行操作。查看这个fiddle...

http://jsfiddle.net/UnsungHero97/HnzyT/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 */

如果你想要垂直和水平居中,你需要知道元素的宽度高度。

希望这可以帮助到你。
Hristo


谢谢!我找到了另一种方法:将绝对定位的div设为100%,并在其中放置一个相对定位的div,使用margin: 0 auto; - Alex
@Alex... 当然可以,但是你需要另一个<div>元素!如果你需要更多的标记,那没问题,只要你得到了你想要的 :) - Hristo
1
我更喜欢这个解决方案:https://dev59.com/BnI-5IYBdhLWcg3wlpiW 你不需要知道尺寸。 - Scotty Waggoner

12

在调整大小时,只需将窗口中点从元素宽度的一半中减去即可。这是一个简单的插件,如果需要,您可以很容易地适应垂直居中:

$.fn.centerMe = function () {
    this.css('left', $(window).width()/2 - $(this).width()/2);
};

$(window).resize(function() { $('#yourElem').centerMe(); });

$('#yourElem').centerMe();

查看可运行的示例 →


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