希望用flex布局实现这个样式,justify-content: space-between无法满足提出的需求

想用flex布局实现下面的样式

左边的两个方块距离左框25px;

右边的两个方块距离右框25px;

中间的方块距离左边和右边为38px;

使用flex-direction: column后

justify-content: space-between 这个特性无法满足上面的需求,请问如何才能实现?

图片描述

阅读 3k
4 个回答

<style type="text/css">

.flex {
    display: flex;
}
.f-j-b {
    justify-content: space-between;
}

.f-d-c {
    flex-direction: column;
}

.bg-g {
    background: green;
}

.bg-r {
    background: red;
}

.bg-y {
    background: yellow;
}

.m-r-5 {
    margin-right: 25px;
}
.m-l-5 {
    margin-left: 25px;
}

.m-b-5 {
    margin-bottom: 25px;
}

.p-5 {
    padding: 25px;
}

.f-1 {
    flex:  1;
}

.f-2 {
    flex: 2;
}

.h10 {
    height: 200px;
}

</style>
<body>

<div class="flex f-j-b p-5" style="width: 550px;height: 300px;background: #ccc">
        <div  class="flex f-d-c f-2 f-j-b ">
            
            <div class="bg-g h10 m-b-5">
            </div>
            <div class="bg-g h10">
            </div>
        </div>
        <div class="m-r-5 m-l-5 f-1  bg-y"></div>
        <div class="flex f-d-c f-2 f-j-b ">
            <div class="bg-r h10 m-b-5 ">
            </div>
            <div class="bg-r h10">
            </div>

        </div>

</div>

</body>

.box{

        display: flex;
        width: 500px;
        height: 500px;
        border: 1px solid #ddd;
        margin: 50px auto 0;
        padding: 25px;
        justify-content: space-between;
    }
    .left,.center.right{
        height: 100px;
    }
    .left,.right{
        flex:1;
        background-color: red;
    }
    .center{
        margin: 0 35px;
        background-color: green;
    }

我先指出你的问题:
1、flex-direction:column 是指纵向排列,而你这问题,明显就不能直接单纯的采用纵向排列
2、justify-content: space-between 是指元素分居空间两侧,而你左右边距和中间边距明显不同,所以,你只能采用margin或者padding来实现,要不然无法实现。

解决办法:
第一:横向排列,三个元素,将左右两边的纵向排列的两个元素直接归为一个元素。
第二:给最外层的容器一个padding:上下左右应该都是25px,然后中间元素给一个左右margin,如果两边的元素的宽度固定,中间宽度自动撑满剩下的空间,反之,亦然。
第三:再来实现左右两侧纵向排列的问题,考虑到分辨率,所以采用flex的纵向排列+margin+flex:1

实现的方法不是唯一的,这个就需要结合你自身的需求来进行灵活的调整。

    <style>
      *{
        margin: 0;
        padding: 0;
      }
      .main {
        width: 600px;
        height: 300px;
        display: flex;
        justify-content: space-between;
        flex-direction: row;
        background: rgb(163, 163, 163);
        box-sizing: border-box;
        padding: 25px;
      }
      .left > div {
        background: rgb(85, 0, 251);
      }
      .right > div {
        background: rgb(245, 0, 8);
      }
      .mid {
        flex: 1;
        box-sizing: border-box;
        margin: 0 38px;
        background: rgb(34, 255, 151);
      }
      .left,
      .right {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 2;
      }
      .left > div,
      .right > div {
        height: calc((100% - 25px) / 2);
      }
    </style>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题