3

I'm trying to have three (yellow framed) labels: A, B, and C.

I want A to be left-aligned and B and C to be right aligned. As I don't want the frame of A to grow until reaching B, I set A's display: inline. This almost seems to work, but for some reason A is misbehaving: it shows up vertically misaligned. This seems to originate from this being the only p element that is not a direct subchild of the flex container. But why does this happen?

enter image description here

body {
  margin: 0px;
}

#main {
  display: flex;
}

.node {
  margin: 0px;
  padding: 16px;
  border: 2px dashed yellow;
}
<div id="main" style="background: red;">
  <div style="flex-grow: 1;">
    <p class="node" style="display: inline;">A</p>
  </div>
  <p class="node">B</p>
  <p class="node">C</p>
</div>

Thanks

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
  • Instead of `display: inline` use `display: inline-block` ([demo](https://jsfiddle.net/Lnge96j5/)). The gap you're seeing underneath "A" is the [space for descenders](https://stackoverflow.com/a/31445364/3597276). – Michael Benjamin Mar 10 '20 at 03:56
  • @Michael_B it's not really the descender. It's due to the fact that padding-top/bottom applied to inline element doesn't affect the layout so his top padding is overflowing from the top instead of pushing the element to the bottom like with B, C – Temani Afif Mar 10 '20 at 12:47
  • @TemaniAfif, good point. That manages to remove most of the gap. But even after the padding issue is resolved, there is still descender space. Switching to `inline-block` solves the problem. – Michael Benjamin Mar 10 '20 at 13:38

1 Answers1

2

Only children (direct descendants) of flex elements have properties of flex-items.

Here you are:

body {
  margin: 0px;
}

#main {
  display: flex;
  background: red;
}

.node {
  margin: 0px;
  padding: 16px;
  border: 2px dashed yellow;
}

.node:first-child {margin-right:auto}
<div id="main" style="background: red;">
  <p class="node">A</p>
  <p class="node">B</p>
  <p class="node">C</p>
</div>
Kosh
  • 16,966
  • 2
  • 19
  • 34
  • Ahh. Seems to work and it's simpler. But I still have the same question: what was setting the whole thing off before? – devoured elysium Mar 10 '20 at 03:18
  • @devouredelysium, when you wrapped `p` into `div`, `div` became a `flex-item` with the corresponding properties. The `p` because of `display:inline` became a regular inline element and was not stretched anymore. – Kosh Mar 10 '20 at 03:22
  • @devouredelysium, because it expands right margin to all available space and pushes A to the left. – Kosh Mar 10 '20 at 03:31
  • Just a quick point on your wording: "direct children" is redundant. All children are direct descendants. – Michael Benjamin Mar 10 '20 at 13:43
  • 1
    @Michael_B, you're absolutely right, but I had to emphasize it =)) fixed. – Kosh Mar 10 '20 at 15:48