问题
I want to create four children that are next to each other. Now, when the viewport-width gets smaller, these are supposed to collaps to a two by two grid. (Less important: When it gets even smaller they shall be 100% of the parent's width.) Now my problem is not to create this with media queries. The problem is that the first child has a bigger height than the height of the second child. When they collaps to a 2 by 2 grid the third child is always placed below the second child and not (how I want it to be) below the first.
I've also tried flexbox but as far as I know there is no possibility to make it either 4 by 1, 2 by 2 or 1 by 4. The problem only occurs in some specific viewport widths because the number of lines is (in some situations) equal in the first and second child.
To see what I mean, here is a snippet:
*{
padding: 0px;
margin: 0px;
}
#parent{
width: 960px;
max-width: 90%;
font-size: 1rem;
margin: auto;
background-color: green;
}
.child{
width: 23%;
margin: 0px 1%;
background-color: yellow;
float: left;
}
@media (max-width: 60rem){
.child{
width: 46%;
margin: 2%;
float: left;
}
}
@media (max-width: 30rem){
.child{
width: 100%;
margin: 0;
float: none;
}
}
<div id="parent">
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
回答1:
You can do it with the Grid:
* {margin: 0; padding: 0; box-sizing: border-box}
#parent {
display: grid;
grid-template-columns: repeat(4, 1fr); /* 4 x 25% / can also use 1fr 1fr 1fr 1fr or 25% 25% 25% 25%, without the repeat(), fr stands for fraction */
grid-gap: 10px; /* 10px horizontal and vertical gap between child elements */
width: 960px;
max-width: 90%;
font-size: 1rem;
margin: auto;
background: green;
}
.child {background: yellow}
@media (max-width: 60rem){
#parent {
grid-template-columns: repeat(2, 1fr); /* 2 x 50% / can also use 1fr 1fr or 50% 50%, without the repeat() */
}
}
@media (max-width: 30rem){
#parent {
grid-template-columns: 1fr; /* 1 x 100% / can also use 100% */
}
}
<div id="parent">
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consetetur</p>
</div>
<div class="child">
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
回答2:
add height property do class .child
来源:https://stackoverflow.com/questions/47237948/how-can-i-make-four-responsove-children-that-change-to-a-2-by-2-grid-when-making