Reputation: 2047
I have two divs that are inside a flexbox. When there is enough space horizontally for them to fit on the same line, they look like this:
When I use the css property flex-wrap: wrap
, the two divs will appear on different lines while floating left:
I want the green one to align to the right side but exist on a separate line as the blue one when the wrapping occurs in flexbox. It would look like this:
How do I do this with flexbox?
Here is the code:
.flexbox {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.blue {
min-height: 50px;
min-width: 300px;
background-color: blue;
}
.green {
min-height: 50px;
min-width: 300px;
background-color: green;
}
<div class="flexbox">
<div class="blue"></div>
<div class="green"></div>
</div>
Upvotes: 3
Views: 1942
Reputation: 371133
The only thing you need to do is add margin-left: auto
to .green
.
.flexbox {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.blue {
min-height: 50px;
min-width: 300px;
background-color: blue;
}
.green {
margin-left: auto; /* NEW */
min-height: 50px;
min-width: 300px;
background-color: green;
}
<div class="flexbox">
<div class="blue"></div>
<div class="green"></div>
</div>
Here's an explanation of how this works:
Upvotes: 9
Reputation: 524
I've edited your code, I added the flex-direction:column;
instead of wrap, then defined align-self
for each flex item
.flexbox{
display:flex;
flex-direction:column;
}
.blue{
min-height:50px;
min-width:300px;
background-color:blue;
align-self: flex-start;
}
.green{
min-height:50px;
min-width:300px;
background-color:green;
align-self:flex-end;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<br>
<br>
<br>
<div class="flexbox">
<div class="blue"></div>
<div class="green"></div>
</div>
</body>
</html>
Upvotes: 1
Reputation: 53674
Remove justify-content
from the parent, and use margin
on one of the children instead to separate them, then use align-self: flex-end
on .green
to align it to the bottom.
.flexbox{
display:flex;
flex-wrap: wrap;
}
.blue{
min-height:50px;
min-width:300px;
background-color:blue;
}
.green{
min-height:50px;
min-width:300px;
background-color:green;
align-self: flex-end;
margin-left: auto;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<br>
<br>
<br>
<div class="flexbox">
<div class="blue"></div>
<div class="green"></div>
</div>
</body>
</html>
Upvotes: 4