左对齐、右对齐和居中对齐的 div

Left, right and center aligned divs

我正在尝试创建一个页面,该页面在一行中包含多个 3 个 div,它们左右对齐并居中。

我尝试使用 float:leftfloat:right,但效果非常糟糕。页面超级随机缩放,我希望 div 在页面缩小时变成 2 列,然后在移动设备上变成 1 列。

.container {
  display: inline-block;
  text-align: center;
  width: 100%;
  position: relative;
}
.left,
.middle,
.right {
  width: 200px;
  height: 200px;
  background-color: red;
  display: inline-block;
}
.left {
  float: left;
}
.right {
  float: right;
}
<div class="container">

  <div class="left">
    <div class="content">
    </div>
  </div>
  <div class="middle">
    <div class="content">
    </div>
  </div>
  <div class="right">
    <div class="content">
    </div>
  </div>

</div>

jsFiddle: https://jsfiddle.net/azizn/j4cgef5g/

这是 flexbox 的教科书用例:

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

举个例子:http://codepen.io/memoblue/pen/XKQqGg

有很多方法可以处理响应方面的问题,但我需要更具体地了解布局在不同断点处的外观,以便为您提供有用的答案…

查看我在下面包含的示例(CSS 和 HTML 脚本)

HTML

<div id='columns'>
    <div id='col1'></div>
    <div id='col2'></div>
    <div id='col3'></div>
</div>

CSS

#columns{
    position: absolute;
    height: 100%;
    width: 100%;
}

#columns #col1{
    float: left;
    width: 33.33%;
    height: 100%;
}


#columns #col2{
    float: left;
    width: 33.33%;
    height: 100%;
}


#columns #col3{
    float: left;
    width: 33.33%;
    height: 100%;
}

@media media only screen and (max-width:1024px) and (min-width:540px){
    #columns #col1{
        width: 50%;
    }


    #columns #col2{
        width: 50%;
    }


    #columns #col3{
        width: 100%;
    }
}

@media media only screen and (max-width:540px){
    #columns #col1{
        width: 100%;
    }


    #columns #col2{
        width: 100%;
    }


    #columns #col3{
        width:  100%;
    }
}

请注意,我还没有实际测试过上面的示例,但它应该可以工作。您可以根据需要编辑宽度和高度值,以及媒体查询的宽度。随着屏幕变小,它会从显示中移除第 3 列和第 2 列,同时使其他列变大。要使三列位于左、中、右位置,您不需要指定不同的浮动,因为在块中,它们会自动碰撞并在左侧堆叠,直到它们到达屏幕边缘。这也是为什么宽度一般只能是33.33%,因为到33.333%一般会让第三个方块因为不够space而被压下去。在大多数情况下,0.01% 的死亡 space 无论如何都不会引人注意。