2016-01-12 94 views
2

有没有办法将绝对div放在他父母的中心位置和z-index内容之上?中心绝对div在另一个div

<div id="parent"> 
    <div id="absolute-centred"></div> 
</div> 

父母的大小是未知的。绝对div应该覆盖内容。

+0

可能的重复[如何在div中居中绝对元素?](http://stackoverflow.com/questions/1776915/how-to-center-absolute-element-in-div) – yeouuu

回答

11

最简单的方式垂直和水平居中一个div到另一个是这样的:

.container { 
 
\t position: relative; 
 
\t width: 100px; /* not part of solution */ 
 
\t height: 100px; /* not part of solution */ 
 
\t background-color: #808; /* not part of solution */ 
 
\t border-radius: 50%; /* not part of solution */ 
 
} 
 
.content { 
 
\t position: absolute; 
 
\t top: 50%; 
 
\t left: 50%; 
 
\t transform: translate(-50%, -50%); 
 
\t text-align: center; /* not part of solution */ 
 
}
<div class="container"> 
 
    <div class="content">I'm absolutly centered</div> 
 
</div>

你也可以嵌套的水平/垂直对齐到另一个absolute定位的div。如果您愿意,您的父母relative可能是absolutefixed

如果你只是想垂直对齐,使用translateY(-50%)如果你想水平对齐,用translateX(-50%)具有互补topleft财产。

最后,您可以将50%更改为您想要的任何内容,而不仅仅是“中心”内容。

+2

我快了一点点但我删除了我的答案,因为你的小提琴。 –

+0

太棒了!非常感谢你。 – Verdemis