gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:27:49 25 4
gpt4 key购买 nike

我正在尝试让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com