CSS: Impossible to Center When Padding Unknown

Viewed 84

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 class="parent">
  <div class="child">
  </div>
</div>

edit: CSS only. Outer HTML OK but nothing between parent/child

2 Answers

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 class="parent">
  <div class="child">
  </div>
</div>

<div class="parent" style="--p:40px;">
  <div class="child">
  </div>
</div>

<div class="parent" style="--p:5px;">
  <div class="child">
  </div>
</div>

Simply add at the top of style.css

* {
  margin: 0 auto;
}
Related