Applying width to an element that has been centered horizontally and vertically using flex loses the properties applied by flex
body {
margin: 0;
padding: 0;
height: 100vh;
}
header {
padding: 10px;
display: flex;
justify-content: space-between;
border-bottom: 1px dashed lightblue;
}
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
min-height: 100vh;
width: 200px; /* if comment this line the properties assigned by flex work properly */
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
ul li {
padding: 10px;
}
<header>
<nav>
<ul>
<li>
<a href="#">Link 1</a>
</li>
<li>
<a href="#">Link 2</a>
</li>
<li>
<a href="#">Link 3</a>
</li>
</ul>
</nav>
<button>Dark mode</button>
</header>
<main>
<h1>Lorem ipsum dolor.</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus
dolorem aliquam amet impedit.
</p>
</main>
What is the reason for this and how should this be implemented correctly?
Update
I get the desired result by modifying the html. I wrap the main content in a div and assign a fixed width to this div. Is it possible to do the same using only CSS?
body {
margin: 0;
padding: 0;
height: 100vh;
}
header {
padding: 10px;
display: flex;
justify-content: space-between;
border-bottom: 1px dashed lightblue;
}
main {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
border: 1px dashed tomato;
}
main div {
width: 200px;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
ul li {
padding: 10px;
}
<header>
<nav>
<ul>
<li>
<a href="#">Link 1</a>
</li>
<li>
<a href="#">Link 2</a>
</li>
<li>
<a href="#">Link 3</a>
</li>
</ul>
</nav>
<button>Dark mode</button>
</header>
<main>
<div>
<h1>Lorem ipsum dolor.</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus
dolorem aliquam amet impedit.
</p>
</div>
</main>
Thanks in advance
