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:
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
The default value of
flex-direction
isrow
, whereas you wantcolumn
:The default value for
flex-direction
isrow
.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 theh1
.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).
Set
flex-direction
tocolumn
to arrange them in a column.