使两个元素的行为像浮动元素,而不使用css属性float

时间:2017-03-03 14:09:33

标签: css flexbox css-float

我想使用css属性float水平对齐两个元素而不是

更具特色:

我希望它们水平对齐,浮动到父级的每一侧:

enter image description here

并且,如果屏幕变小,我希望它们在彼此下面包裹,同时仍然漂浮到父母的每一边(就像浮动一样):

enter image description here

这可以实现使用flexbox或类似的吗?

3 个答案:

答案 0 :(得分:2)

我没有意识到只根据子元素的属性制作左右交换边的方法,就像真正的浮点数一样,而不在包装器上指定flex-direction:row-reverse;。请参阅我的示例进行比较: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;
}

答案 1 :(得分:0)

第一财产:

.container{
    display: flex;
    justify-content: space-between;
}

第二个属性(为特定分辨率添加了媒体查询):

.container{
    flex-direction: column;
}
.1stDiv{
    margin-right: auto;
}
.2ndDiv{
    margin-left: auto;
}

margin-left:auto margin-right:auto 的工作方式类似于flexbox的浮动。

响应版本的其他想法:

.container{
        flex-direction: column;
    }    
.1stDiv{
    align-self: flex-start;
}
.2ndDiv{
    align-self: flex-end;
}

答案 2 :(得分:0)

#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;
}

Fiddle link