I've encountered a surprising conundrum while working towards an answer for Align the green box with the grey box.
Is it impossible to center (without resizing) a child div against a parent div with asymmetric padding without knowing the padding amount no matter the positioning (float/absolute/static) or display (flex/grid/block/inline) or anything else?
In other words, for any value of X
and any widths != 0
, center child against parent so that the distance for each side from blue/red to red/white is the same.
.parent {
width: 10em;
padding-right: X;
background: red;
}
.child {
width: 4em;
height: 4em;
background: blue;
}
<div >
<div >
</div>
</div>
CodePudding user response:
one way is to add margin auto in child class
margin-right: auto;
margin-left: auto;
.parent {
width: 10em;
padding-right: 1200;
background: red;
}
.child {
width: 4em;
height: 4em;
background: blue;
margin-right: auto;
margin-left:auto
}
<div >
<div >
</div>
</div>
CodePudding user response:
If you can consider the padding as a variable then you can do like below:
.parent {
--p:20px;
width: 10em;
padding-right: var(--p);
background: red;
}
.child {
width: 4em;
height: 4em;
background: blue;
margin:auto;
left:calc(var(--p)/2);
position:relative;
}
<div >
<div >
</div>
</div>
<div style="--p:40px;">
<div >
</div>
</div>
<div style="--p:5px;">
<div >
</div>
</div>
CodePudding user response:
Simply add at the top of style.css
* {
margin: 0 auto;
}