中心绝对div在另一个div中

Ver*_*mis 4 html css3

有没有办法将一个绝对div放在他的父母居中,并在z-index的内容之上?

<div id="parent">
    <div id="absolute-centred"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

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

Bru*_*eur 15

将div垂直和水平居中的简单方法如下:

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

您还可以将水平/垂直对齐嵌套到另一个absolute定位的div.您的父母relative可以是absolute,或者fixed如果您愿意.

如果您只想垂直对齐,请使用translateY(-50%),如果您想要水平对齐,请使用translateX(-50%)互补topleft属性.

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

  • 我的速度要快一点,但我删除了我的答案,因为你的小提琴. (3认同)