首页 > 解决方案 > 是否可以在不增加大小的情况下在项目中添加间距?

问题描述

我正在尝试在列之间添加空间(位于带有“display:flex;”的容器内),但是例如,如果我为其中任何一个添加边距,假设我有 2 个宽度为 50% 的列。我想到在列之间“添加”一些空间以便它们不会粘在一起的唯一方法是创建另一个容器只是为了添加边距、bg-color、填充等。

基于 12 列的网格示例,其中一切正常:

    <!DOCTYPE html>
    <html>
    
    <head>
        <style>
            *,
            *::after,
            *::before {
                margin: 0;
                box-sizing: border-box;
            }
    
            .row {
                display: flex;
                flex-flow: row wrap;
            }
    
            /* based on 12 columns */
            .col-hd-3 {
                width: 25%;
            }
        </style>
    </head>
    
    <body>
        <div class="row">
            <div class="col-hd-3" style="background-color: red;">
                test
            </div>
            <div class="col-hd-3" style="background-color: green;">
                test
            </div>
            <div class="col-hd-3" style="background-color: yellow;">
                test
            </div>
            <div class="col-hd-3" style="background-color: grey;">
                test
            </div>
        </div>
    </body>
    
    </html>

现在,假设我向任何列添加边距:

    <! ---->
    <div class = "row">
             <div class = "col-hd-3" style = "background-color: red; margin: 12px;">
                 test
             </ div>
    <! ---->

最后一列将转到下一行。

所以解决它的唯一方法是:

    <!---->
    <div class="row">
            <div class="col-hd-3">
                <div style="margin: 12px; padding: 5px; background-color: red;">
                    Test
                </div>
            </div>
    <!---->

我确定解决方案,还是做错了什么?

标签: cssflexbox

解决方案


因此,当您使用display: flex时,您需要在列上设置flex-grow: 1;andflex-basis: 0;或简单地设置flex: 1;. 阅读:https ://www.w3schools.com/cssref/css3_pr_flex.asp

flex-grow定义了弹性项目在必要时增长的能力,并定义flex-basis了在剩余空间分配之前元素的默认大小。

所以:

.col-hd-3 {
   max-width: 25%; /* COLUMN WILL NOT BE WIDER THAN 25% */
   margin: 12px;
   flex-basis: 0;
   flex-grow: 1;
}

或者您可以使用flex速记:

.col-hd-3 {
    max-width: 25%; /* COLUMN WILL NOT BE WIDER THAN 25% */
    margin: 12px;
    flex: 1;
}

*,
*::after,
*::before {
    margin: 0;
    box-sizing: border-box;
}

.row {
    display: flex;
    flex-flow: row wrap;
}

/* based on 12 columns */
.col-hd-3 {
    width: 25%;
    margin: 12px;
    flex-basis: 0;
    flex-grow: 1;
}
<div class="row">
      <div class="col-hd-3" style="background-color: red;">
          test
      </div>
      <div class="col-hd-3" style="background-color: green;">
          test
      </div>
      <div class="col-hd-3" style="background-color: yellow;">
          test
      </div>
      <div class="col-hd-3" style="background-color: grey;">
          test
      </div>
  </div>


推荐阅读