Reputation: 385
I want to horizontally align two elements without using the css property float.
To be more spesific:
I want them to be horizontally aligned, floating to each side of the parent:
And, if the screen gets smaller, I want them to wrap underneath each other while still floating to each side of the parent (like with float):
Is this possible to achieve using flexbox or something like that?
Upvotes: 0
Views: 1386
Reputation: 195
I'm not aware of a way to make the left and right swap sides based on only a property of a child element like a real float does, without specifying flex-direction:row-reverse;
on the wrapper. See my example for a comparison: http://codepen.io/ijstanley/pen/JWXwOy
<p>pseudo floats in reverse order in markup</p>
<div class="flex wrapper">
<div class="pseudo float right">right</div>
<div class="pseudo float left">left</div>
</div>
<p>pseudo floats in correct order in markup</p>
<div class="flex wrapper">
<div class="pseudo float left">left</div>
<div class="pseudo float right">right</div>
</div>
<p>pseudo floats in reverse order in markup, reverse flex direction</p>
<div class="reverse flex wrapper">
<div class="pseudo float right">right</div>
<div class="pseudo float left">left</div>
</div>
<p>pseudo floats in correct order in markup, reverse flex direction</p>
<div class="reverse flex wrapper">
<div class="pseudo float left">left</div>
<div class="pseudo float right">right</div>
</div>
<p>actual floats</p>
<div class="floater wrapper">
<div class="real float left">left</div>
<div class="real float right">right</div>
</div>
.wrapper {
border:3px solid gray;
}
.wrapper.flex {
display:flex;
flex-direction:row;
flex-wrap:wrap;
justify-content:space-between;
}
.wrapper.flex.reverse {
flex-direction:row-reverse;
}
.wrapper.floater {
width:100%;
}
.wrapper.floater::after {
content:'';
display:block;
clear:both;
}
.float {
min-height:200px;
background:red;
border:3px solid black;
width:300px;
}
.float.pseudo.left {
margin-right:auto;
}
.float.real.left {
float:left;
}
.float.real.right {
float:right;
}
Upvotes: 2
Reputation: 566
1st property:
.container{
display: flex;
justify-content: space-between;
}
2nd property(media query added for certain resolution):
.container{
flex-direction: column;
}
.1stDiv{
margin-right: auto;
}
.2ndDiv{
margin-left: auto;
}
margin-left:auto and margin-right: auto works like a float for a flexbox.
OTHER IDEA FOR THE RESPONSIVE VERSION:
.container{
flex-direction: column;
}
.1stDiv{
align-self: flex-start;
}
.2ndDiv{
align-self: flex-end;
}
Upvotes: 0
Reputation: 2472
#first{
width:50px;
height:50px;
position:absolute;
left:0px;
right:auto;
top:0px;
background-color:red;
}
#second{
width:50px;
height:50px;
position:absolute;
left:auto;
right:0px;
top:0px;
background-color:green;
}
Upvotes: 0