且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将绝对定位的元素居中放置在 div 中?

更新时间:2023-10-09 13:54:34

响应式解决方案

如果您不需要支持 IE8 及更低版本,这是一个很好的响应式设计或未知尺寸的解决方案.

.center-axis-x {位置:绝对;左:50%;变换:翻译(-50%,0);}

.outer {位置:相对;/* 或绝对 *//* 不必要的样式属性 */保证金:5%;宽度:80%;高度:500px;边框:1px纯红色;}.内{位置:绝对;左:50%;顶部:50%;变换:翻译(-50%,-50%);/* 不必要的样式属性 */最大宽度:50%;文本对齐:居中;边框:1px纯蓝色;}

<div class="inner">我总是居中<br/>不管我有多少文本、高度或宽度.<br/>尺寸或我的父母也无关紧要</div>

这是一个 JS Fiddle

线索是,left: 50% 是相对于父元素的,而 translate 变换是相对于元素的宽度/高度.

这样你就有了一个完美居中的元素,在子元素和父元素上都有一个灵活的宽度.奖励:即使孩子比父母大,这也有效.

你也可以用这个垂直居中(同样,父母和孩子的宽度和高度可以完全灵活(和/或未知)):

.center-axis-xy {位置:绝对;左:50%;顶部:50%;变换:翻译(-50%,-50%);}

请记住,您可能还需要 transform 供应商前缀.例如 -webkit-transform: translate(-50%,-50%);

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;
}

How can I do it?

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>

Here is a JS Fiddle

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%);
}

Keep in mind that you might need transform vendor prefixed as well. For example -webkit-transform: translate(-50%,-50%);