Given
.parent {
display: flex;
justify-content: center;
align-items: center;
}
In the snippet below, the absolutely positioned child is centered:
.parent, .child {
border-radius: 0.25rem;
}
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 10rem;
height: 10rem;
background-color: #eee;
}
.child {
position: absolute;
width: 1rem;
height: 1rem;
background-color: #444;
}
<div class='parent'>
<div class='child'></div>
</div>
However in the following example this isn't the case for the h1
which is a direct child of a flex parent. The only meaningful difference I can think of is the padding on it's parent. My question is how can padding of the parent effect an absolutely positioned child? - if this is the case?
Given that absolutely positioned children are removed from the normal flow of the document.
* {
box-sizing: border-box; margin: 0; padding: 0;
}
html, body {
height: 100%;
}
html {
transform: scale( 0.45);
}
body, .parent {
display: flex;
justify-content: center; align-items: center;
padding: 4rem;
font-family: Arial;
color: #444;
}
.wrap {
border-radius: 1rem;
width: 100%;
padding: 2rem;
background-color: #eee;
}
.parent, h1 {
position: relative;
border-radius: 0.5rem;
padding-top: 50%;
background-color: #ddd;
}
h1 {
position: absolute;
padding: 1rem;
background-color: #fff;
}
<div class='wrap'>
<div class='parent'>
<h1>heading</h1>
</div>
</div>
Why isn't the h1
above vertically centered?
`, does it behave as you'd like it to?
– Eyal May 23 '21 at 21:19