如何将绝对定位的元素居中放置在 div 中? [英] How can I center an absolutely positioned element in a div?

查看:29
本文介绍了如何将绝对定位的元素居中放置在 div 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在窗口中央放置一个 div(带有 position:absolute;)元素.但是我在这样做时遇到了问题,因为宽度未知.

我试过了.但需要调整,因为宽度是响应式的.

.center {左:50%;底部:5px;}

我该怎么做?

解决方案

响应式解决方案

如果您不需要支持 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%);

这篇关于如何将绝对定位的元素居中放置在 div 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆