Search code examples
cssflexboxalignment

Div block and paragraph are not aligned when align-items is set to flex-start or flex-end


In a flexbox, paragraphs and div blocks do not use the same line to align themselves when the property align-items is set to flex-start or flex-end. With flex-end, the div is "hanging" whereas the paragraphs are "laying". As you can see in this example, the top border of the div element is aligned to the bottom of the paragraphs. (With a narrow flexbox that forces the text to take several lines, it is not clear how the div block aligns exactly but it is still hanging.)

.flexbox {
  display: flex;
  align-items: flex-end;
  background-color: yellow;
}
.flexbox p {
  background-color: blue;
}
.flexbox div {
  background-color: red;
}
<div class=flexbox>
  <p>This is a paragraph.</p>
  <p>This is a paragraph<br>split in two lines</p>
  <div>This is not a paragraph.</div>
</div>

I tried various things including nesting my paragraphs in divs, but the alignment remains the same. I also played with the display property but the issue doesn't seem to be related to that.

In the real case, I have links containing svg images inside my div, this is a simplified example.


Solution

  • The browser sets default margins on paragraph elements, but not divs.

    enter image description here

    Override these margins.

    .flexbox {
      display: flex;
      align-items: flex-end;
      background-color: yellow;
    }
    .flexbox p {
      margin: 0; /* new */
      background-color: blue;
    }
    .flexbox div {
      background-color: red;
    }
    <div class=flexbox>
      <p>This is a paragraph.</p>
      <p>This is a paragraph<br>split in two lines</p>
      <div>This is not a paragraph.</div>
    </div>