[英]css/ jQuery - center absolute positioned div
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;
won't work for elements that are absolutely positioned.不适用于绝对定位的元素。 Instead, we can work with the properties of the element itself.
相反,我们可以使用元素本身的属性。 Check out the fiddle...
看看小提琴...
http://jsfiddle.net/UnsungHero97/HnzyT/2/ http://jsfiddle.net/UnsungHero97/HnzyT/2/
To center it horizontally is easy since you know the width AND its 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 AND how tall the element is.如果您想将其垂直和水平居中,您需要知道元素的宽度和高度。
I hope this helps.我希望这有帮助。
Hristo赫里斯托
Just subtract the window midpoint from half the width of you element on resize.只需在调整大小时从元素宽度的一半中减去 window 中点。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.