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

标签 javascript jquery css

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/

相关文章:

javascript - HTML 元素从节点列表中消失

javascript - 如何使用 angular.js 将 JavaScript 数组变量值传递给 html

javascript - 在javascript中对并行数组进行排序

jquery - 跨域 JSON 调用

javascript - 使用 jquery 在内容之间切换的简单方法

javascript - 如何隐藏 iPhone 上的地址栏?

javascript - 你如何链接 promise 但将类型从一个然后更改为另一个?

javascript - 如何在使用 JQuery 到达最后一张幻灯片时不显示下一张幻灯片?

javascript - Bootstrap 4 "All"选项卡

html - 如何使div响应