javascript css/ jQuery - 居中绝对定位 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5811957/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:26:14  来源:igfitidea点击:

css/ jQuery - center absolute positioned div

javascriptjquerycss

提问by Alex

The div is 50% opaque and is displayed on top of the site's content, and it has a fixed width of 960 pixels (it's created by jQuery).

div 是 50% 不透明的,显示在网站内容的顶部,它的固定宽度为 960 像素(由 jQuery 创建)。

How can I center it horizontally?

如何将其水平居中?

margin: 0 auto;doesn't work :(

margin: 0 auto;不起作用:(

回答by Hristo

margin: 0 auto;won't work for elements that are absolutely positioned. Instead, we can work with the properties of the element itself. Check out the fiddle...

margin: 0 auto;不适用于绝对定位的元素。相反,我们可以使用元素本身的属性。看看小提琴...

http://jsfiddle.net/UnsungHero97/HnzyT/2/

http://jsfiddle.net/UnsungHero97/HnzyT/2/

To center it horizontally is easy since you know the width ANDits positioned absolutely. All you have to do is give it 2 CSS properties:

使其居中水平是容易的,因为你知道宽度它的绝对位置。你所要做的就是给它 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 */

If you want to center it both vertically and horizontally, you need to know how wide ANDhow tall the element is.

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

I hope this helps.
Hristo

我希望这有帮助。
赫里斯托

回答by mVChr

Just subtract the window midpoint from half the width of you element on resize. Here's a simple plugin that you could easily accomodate to center vertically if need be as well:

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

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

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

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

See working example →

参见工作示例 →