Reputation: 5943
Problem:
A container that has three boxes is positioned in the center in desktop view. However, it is not in the center when viewed on a mobile.
Minimal Working Example (MWE):
HTML
<article>
<section class="category cars">Cars</section>
<section class="category food">Food</section>
<section class="category drinks">Drinks</section>
</article>
CSS
/* Reset */
* {
margin: 0;
padding: 0;
}
/* Layout */
article {
display: flex;
justify-content: center;
width: 100%;
}
.category {
height: 50px;
width: 200px;
color: white;
text-align: center;
font-size: 1.5rem;
padding: 1rem;
}
/* Background colors */
.cars {
background-color: crimson;
}
.food {
background-color: lightseagreen;
}
.drinks {
background-color: deepskyblue;
}
/* Mobile view */
@media screen and (max-width: 600px) {
article {
flex-direction: column;
}
}
Current output:
The three boxes are positioned to the left.
Desired output:
The three boxes should center in the middle on a mobile view.
Upvotes: 2
Views: 2994
Reputation: 218
You can do that by adding a parent element to the <article>
tag. Then, add display: flex; width: 100%;justify-content: center;
to the parent element ONLY IN THE MEDIA QUERY.
This will make the <article>
tag come in the center. The parent element has background: none
which makes it look like the <article>
container is in the middle
/* Reset */
* {
margin: 0;
padding: 0;
}
/* Layout */
article {
display: flex;
justify-content: center;
width: 100%;
}
.category {
height: 50px;
width: 200px;
color: white;
text-align: center;
font-size: 1.5rem;
padding: 1rem;
}
/* Background colors */
.cars {
background-color: crimson;
}
.food {
background-color: lightseagreen;
}
.drinks {
background-color: deepskyblue;
}
/* Mobile view */
@media screen and (max-width: 600px) {
article {
flex-direction: column;
}
.parent{
width: 100%;
display: flex;
justify-content: center;
}
}
<div class="parent">
<article>
<section class="category cars">Cars</section>
<section class="category food">Food</section>
<section class="category drinks">Drinks</section>
</article>
</div>
OR
You could add align-items: center
to the column because you have set flex-direction: column
to the <article>
tag so in this case align-items
will work like justify-content
I hope it helped!
OR
You could use relative positioning. Adding left: 50%;position: relative;transform: translateX(-50%);
to the article in media query will also help IN SOME CASES
Upvotes: 1
Reputation: 177
The solution is pretty simple.
When you change the direction to column
the axis gets reversed too. So, adding align-items: center;
will center the boxes.
This is what you need:
@media screen and (max-width: 600px) {
article {
flex-direction: column;
align-items: center;
}
}
Upvotes: 2