如何在div中将绝对定位的元素居中? [英] How can I center an absolutely positioned element in a div?
问题描述
我需要在窗口中心放置一个div
(带有position:absolute;
)元素.但是我遇到了问题,因为宽度未知.
I need to place a div
(with position:absolute;
) element in the center of my window. But I am having problems doing so, because the width is unknown.
我尝试了这个.但是需要根据宽度进行调整.
I tried this. But it needs to be adjusted as the width is responsive.
.center {
left: 50%;
bottom: 5px;
}
我该怎么办?
推荐答案
自适应解决方案
如果您不需要支持IE8或更低版本,那么对于响应式设计或未知尺寸,这是一个很好的解决方案.
Responsive Solution
Here is a good solution for responsive design or unknown dimensions in general if you don't need to support IE8 and lower.
.centered-axis-x {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
.outer {
position: relative; /* or absolute */
/* unnecessary styling properties */
margin: 5%;
width: 80%;
height: 500px;
border: 1px solid red;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* unnecessary styling properties */
max-width: 50%;
text-align: center;
border: 1px solid blue;
}
<div class="outer">
<div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>
线索是,left: 50%
是相对于父级的,而translate
转换是相对于元素的宽度/高度的.
The clue is, that left: 50%
is relative to the parent while the translate
transform is relative to the elements width/height.
这样,您将拥有一个完美居中的元素,并且在子元素和父元素上都具有灵活的宽度.奖励:即使孩子比父母大,这也有效.
This way you have a perfectly centered element, with a flexible width on both child and parent. Bonus: this works even if the child is bigger than the parent.
您还可以以此将它垂直居中(同样,父母和孩子的宽度和高度可以完全灵活(和/或未知)):
You can also center it vertically with this (and again, width and height of parent and child can be totally flexible (and/or unknown)):
.centered-axis-xy {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
请记住,您可能还需要前缀transform
供应商.例如-webkit-transform: translate(-50%,-50%);
Keep in mind that you might need transform
vendor prefixed as well. For example -webkit-transform: translate(-50%,-50%);
这篇关于如何在div中将绝对定位的元素居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!