【问题标题】:How can I use flexbox to make two items one center one bottom如何使用 flexbox 使两个项目一个中心一个底部
【发布时间】:2022-01-21 15:20:34
【问题描述】:

https://i.stack.imgur.com/e2n5o.png

我想通过flexbox实现这样的布局。 body 是弹性容器,只有两个弹性项目,一张卡片和一个页脚。这是simplified codepen link。如何在卡片位置居中时将页脚放在页面底部。

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;  
}

.container {  
  width: 400px;
  height: 300px;
  background-color: green;
}

.footer {  
  margin-bottom: 20px;
  background-color: yellow;
  width: 200px;
  height: 50px;
}
<div class="container"></div>
<div class="footer"></div>

如果我添加margin-top:auto,页脚的位置会正确,但容器会到顶部。

如果我将gap 添加到body,容器将不在中心

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

    为绿卡使用另一个元素并使用flex-grow: 1 使.container 填充所有可用空间。

    .container 上使用display: flexalign-items:center 使卡片垂直居中。

    body{
      display:flex;
      flex-direction:column;
      align-items:center;
      height:100vh;  
    }
    
    .container{  
      flex-grow: 1;
      display: flex;
      align-items: center;
    }
    
    .card {
      width:400px;
      height:300px;
      background-color:green;
    
    }
    .footer{  
      margin-bottom:20px;
      background-color:yellow;
      width: 200px;
      height:50px;
    }
    <div class="container">
      <div class="card"></div>
    </div>
    <div class="footer"></div>

    body 不需要justify-content:center;,所以你也应该删除它。

    如果您希望 .container 具有 100% 宽度,则另一种方法。

    body {
      display: flex;
      flex-wrap: wrap;
      height: 100vh;
    }
    
    .container {
      width: 100%; /* NEW */
      
      flex-grow: 1;
      display: flex;
      align-items: center;
      justify-content: center;  /* NEW */
    }
    
    .card {
      width: 400px;
      height: 300px;
      background-color: green;
    }
    
    .footer {
      margin-bottom: 20px;
      background-color: yellow;
      width: 200px;
      height: 50px;
      margin: auto; /* NEW */
    }
    <div class="container">
      <div class="card"></div>
    </div>
    <div class="footer"></div>

    【讨论】:

      【解决方案2】:

      您可以使用grid 使容器居中,并定位以粘贴页脚。

      body {
        display: grid;
        place-content: center; /* center the container */
        height: 100vh;
        margin: 0;
      }
      
      .container {
        width: 400px;
        height: 300px;
        background-color: green;
      }
      
      .footer {
        justify-self: center; /* center the footer */
        margin-bottom: 20px;
        background-color: yellow;
        width: 200px;
        height: 50px;
        
        /* push the footer to the bottom */
        position: sticky; 
        top: 100vh;
      }
      <div class="container"></div>
      <div class="footer"></div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        • 2016-01-31
        • 2017-07-01
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        相关资源
        最近更新 更多