The following page shows two rectangles, red and blue. Display is flex. It is expected that red one was placed at the left part of the page (margin-right: auto
) while blue div was centered in the remaining of the page (justify-content: center
).
However, the result is that blue div appears totally at the right of the page instead of centered. I'm not understanding something of flexbox.
body {
display: flex;
justify-content: center;
}
#redDiv {
width: 5em;
height: 10em;
background-color: red;
margin-right: auto;
}
#blueDiv {
width: 10em;
height: 10em;
background-color: blue;
}
<div id="redDiv"></div>
<div id="blueDiv"></div>
Update:
Thanks to all for the information and suggestions. Following them, the final code has been:
body {
display: flex;
}
#redDiv {
width: 5em;
height: 10em;
background-color: red;
margin-right: auto;
}
#auxDiv {
flex: 1 1 auto;
display: flex;
justify-content: center;
}
#blueDiv {
width: 10em;
height: 10em;
background-color: blue;
}
<!DOCTYPE html>
<html>
<body>
<div id="redDiv"></div>
<div id="auxDiv">
<div id="blueDiv"></div>
</div>
</body>
</html>
Update 2:
This solution, based on comments by Temani Afif, gives same result:
body {
display: flex;
}
#redDiv {
width: 5em;
height: 10em;
background-color: red;
}
#blueDiv {
width: 10em;
height: 10em;
background-color: blue;
margin: auto;
}
<!DOCTYPE html>
<html>
<body>
<div id="redDiv"></div>
<div id="blueDiv"></div>
</div>
</body>
</html>