Reputation: 3715
With typical CSS I could float one of two columns left and another right with some gutter space in-between. How would I do that with flexbox?
#container {
width: 500px;
border: solid 1px #000;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
#a {
width: 20%;
border: solid 1px #000;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
}
<div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div>
Upvotes: 198
Views: 316818
Reputation: 1011
In addition to Jost's answer, if you need to align it vertically too, use align-items: center;
if needed.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
align-items: center;
}
Upvotes: 2
Reputation: 11706
Another option is to add another tag with flex: auto
style in between your tags that you want to fill in the remaining space.
https://jsfiddle.net/tsey5qu4/
The HTML:
<div class="parent">
<div class="left">Left</div>
<div class="fill-remaining-space"></div>
<div class="right">Right</div>
</div>
The CSS:
.fill-remaining-space {
flex: auto;
}
This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.
Upvotes: 20
Reputation: 22723
There are different ways but simplest would be to use the space-between see the example at the end
#container {
border: solid 1px #000;
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 10px;
height: 50px;
}
.item {
width: 20%;
border: solid 1px #000;
text-align: center;
}
Upvotes: 2
Reputation: 4239
I came up with 4 methods to achieve the results. Here is demo
Method 1:
#a {
margin-right: auto;
}
Method 2:
#a {
flex-grow: 1;
}
Method 3:
#b {
margin-left: auto;
}
Method 4:
#container {
justify-content: space-between;
}
Upvotes: 53
Reputation: 240858
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#a {
width: 20%;
border: solid 1px #000;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
}
<div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div>
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {
width: 500px;
border: solid 1px #000;
display: flex;
}
#a {
width: 20%;
border: solid 1px #000;
margin-right: auto;
}
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
<div id="container">
<div id="a">
a
</div>
<div id="b">
b
</div>
</div>
Upvotes: 411