Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center absolute div in another div

Tags:

html

css

is there a way to place a absolute div inside his parent centered and above the content with z-index?

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

The size of the parent is unknown. the absolute div should be overlaying the content.

like image 370
Verdemis Avatar asked Jan 12 '16 10:01

Verdemis


1 Answers

The easy way to vertically and horizontally center a div into another goes like this:

.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 */
}
<div class="container">
    <div class="content">I'm absolutly centered</div>
</div>

You could also nest your horizontal/vertical alignment to another absolute positioned div. Your parent relative could be an absolute, or fixed if you prefer.

If you just want vertical align, use translateY(-50%) and if you want horizontal align, use translateX(-50%) with complementary top or left property.

And last, you could change 50% to whatever you want to not only « center » content.

like image 73
Bruno J. S. Lesieur Avatar answered Oct 12 '22 13:10

Bruno J. S. Lesieur