html - 居中对齐固定位置的div

标签 html css alignment css-position center

我正在尝试让 position:fixed 在我的页面上居中对齐的 div。

我总是能够使用这个“hack”来使用绝对定位的 div 来做到这一点

left: 50%; 
width: 400px; 
margin-left: -200px;

...其中 margin-left 的值是 div 宽度的一半。

这对于固定位置的 div 似乎不起作用,相反它只是将它们的最左边的 Angular 放在 50% 处并忽略 margin-left 声明。

关于如何解决这个问题以便我可以将固定定位的元素居中对齐有什么想法吗?

如果你能告诉我一个比我上面概述的方法更好的居中对齐绝对定位元素的方法,我将投入额外的 M&M。

最佳答案

Koen's answer元素没有完全居中。

正确的方法是使用 CSS3 transform 属性,尽管它是 not supported in some old browsers .我们甚至不需要设置固定或相对的 width

.centered {
    position: fixed;
    left: 50%;
    transform: translate(-50%, 0);
}

.almost-centered {
    background-color: #eee;
    position: fixed;
    width: 40%;
    text-align: center;
    top: 5%;
    left: 50%;
    padding: 20px;
    margin-left: -20%;
}

.centered {
    background-color: #eee;
    position: fixed;
    width: 40%;
    text-align: center;
    top: 25%;
    left: 50%;
    padding: 20px;
    transform: translate(-50%, 0);
}
<div class="almost-centered">
    I'm almost centered DIV lorem ipmsum
</div>

<div class="centered">
    I'm exactly centered DIV using CSS3
</div>

关于html - 居中对齐固定位置的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861247/

相关文章:

python - 在 Python 中提取一些 HTML 标记值

html - 需要在 &lt;textarea&gt; &lt;input type ="text"> 中调整 Bootstrap 图标

CSS:多行文本的背景颜色?

python - 在python中对齐DNA序列

php - 循环内带有数组的复选框 False 结果?

html - 如何水平对齐元素?

html - Off Canvas 导航仅在移动设备页面底部创建空白

html - 内联表单使输入文本全宽且响应迅速

html - Bootstrap 。为什么 div 没有响应?

twitter-bootstrap - Bootstrap 网格水平对齐元素