skip to Main Content

I came across a situation that I don’t really understand. I wanted to center two elements and after reading the article below, I decided to use flexbox to do that.

https://www.freecodecamp.org/news/how-to-center-anything-with-css-align-a-div-text-and-more/

I applied "display: flex" and "justify-content: center" to the parent element which in my case is .

HTML

<body>
    <h1>This is the title</h1>
    <div>This is a paragraph</div>
</body>

CSS

body {
    display: flex;
    justify-content: center;
}

After this, my page looks as in the picture below:
Output

Taking into account that HTML elements should be positioned one below another, I don’t understand why it’s not happening in my case. The is positioned above the element. If I remove the CSS part, their vertical order gets back to normal – above the .

What is doing the CSS part so that the natural vertical order of the elements is ignored?

Thank you.

2

Answers


  1. The default value of flex-direction is row, whereas you want column:

    body {
      display: flex;
      flex-direction: column;
    }
    
    body > * {
      border: 1px solid #000;
      align-self: center;
    }
    <h1>This is the title</h1>
    <div>This is a paragraph</div>
    Login or Signup to reply.
  2. The default value for flex-direction is row.

    The elements are not in a reversed order, they are side-by-side (and centred horizontally).

    The default margins on the elements just means that the text inside the p appears higher than the text inside the h1.

    You can see this by setting an outline on the elements (or by clicking the flex button next to the body element in the DOM inspector in your browser’s developer tools).

    #container {
        display: flex;
        justify-content: center;
    }
    
    #container > * {
        outline: dotted blue 1px;
    }
    <div id="container">
    <h1>This is the title</h1>
        <div>This is a paragraph</div>
    </div>

    Set flex-direction to column to arrange them in a column.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search