0

My issue

Usually when using percentages inside a margin property the browser uses the width of the nearest positioned ancestor as reference length. However I'd like to set the margins of my element relative to its parent's height. Is that somehow possible? Or am I stuck with a JavaScript solution?

An example

Specifically I'd like the following:

.child {
  height: 1em;
  width: 1em;
  background: red;
  display: inline-block;
  margin: calc((100% - 1em) / 2);
  /* margin: calc((5em - 1em) / 2); In absolute units */
  /* margin-sizing: height; If only there was some magical property like this... */
}
.container {
  background: green;
  height: 5em;
  width: 15em;
  position: relative;
}
<div class="container">
  <div class="child"></div>
  Something
</div>

To look like this:

Expectation

I know that I could use absolute units in the example above. However I may not always know the exact height of the parent in a more complex or dynamic example. And I'd like to avoid JavaScript for this.

Edit

I should clarify something. My end goal is that the red div in the example above is centered vertically but also has the same distance to the left as it has to the top/bottom. Obviously I'm not bound to specifically use the margin properties. But the outcome of your solution should be the same.

Scindix
  • 1,254
  • 2
  • 15
  • 32
  • I wanted the child to be centered vertically, but at the same time I want it to have the same distance to the left as it has to the top/bottom. Maybe I should have worded my question differently. – Scindix Nov 25 '20 at 08:16
  • 1
    Javascript is your only option here. There is css property or value that can do this. – Paulie_D Nov 25 '20 at 10:19

1 Answers1

1

If you can just use margin or padding then you are stuck because the top and bottom of these properties are relative to the parent's width when used as percentages (as you mentioned already).

The only solution I see is keep the parent element in position: relative and use top & bottom to the child element (which is in position: absolute) to use in percentages.

.child {
  height: 1em;
  width: 1em;
  background: red;
  display: inline-block;
  --calc: calc((100% - 1em) / 2);
  top: var(--calc);
  left: var(--calc);
  right: var(--calc);
  bottom: var(--calc);
  position: absolute;
  /* margin: calc((5em - 1em) / 2); In absolute units */
  /* margin-sizing: height; If only there was some magical property like this... */
}
.container {
  background: green;
  height: 5em;
  width: 15em;
  position: relative;
}
<div class="container">
  <div class="child"></div>
  Something
</div>
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • But the the parent will require a fixed height which is not what the OP wants I believe – Paulie_D Nov 25 '20 at 10:20
  • Even if the parent doesn't have the height or has a dynamic height, this should work. So does the flexbox too which I think can be an alternative solution (a better one). – Mr_Green Nov 25 '20 at 10:32