首页 > 解决方案 > Flexbox 布局 - 等高和 fittext

问题描述

我正在尝试使用 flexbox 构建一个基本的用户界面,到目前为止我有这个..

  body,html {
  margin:0;
  padding:0;
  height:100%;
  }
  
  .container {
    height:100%;
    display:flex;
    flex-direction:column;
  }

  .top {
    flex:4;
    display:flex;
    background:wheat;
    align-items: center;
    justify-content: center;
  }

  .bottom {
    flex:1;
    background:teal;
  }

  .bottom_content {
    display:flex;
    flex-direction:column;
  }

  .section1 {
    flex:1;
    font-size:20px;
    text-align:center;
  }

  .section2 {
    flex:1;
  }
  
  .btn {
    background:red;
    color:white;
    padding:20px;
  }
<div class="container">

  <div class="top">
    <span>TOP CONTENT</span>
  </div>
  
  <div class="bottom">
    
    <div class="bottom_content">
      
      <div class="section1">
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus quam, blandit non lacus in, venenatis tempor dolor. Aliquam in lectus lacus. </span>
      </div>
      
      <div class="section2">
        <div class="btn">
          THIS IS A BUTTON
        </div>
      </div>
    
    </div>
  
  </div>

  
</div>

我正在努力实现这一目标......

在此处输入图像描述

如何使底部具有相同的高度并使其中的内容垂直和水平居中?

我还计划使用 fittext.js 或类似的东西来使按钮和上面的文本适合弹性项目。

我哪里错了?

标签: htmlcssflexboxfittextjs

解决方案


问题

您当前代码的问题.bottom是没有填充可用空间,并且正在使用默认对齐和对齐方式。

修复

可以通过执行以下操作来实现所需的输出:

  • flex:1;.section1和中删除.section2。这会阻止这些divs 扩展以填充可用空间
  • 添加align-items: center;justify-content: space-evenly;.bottom_content。这将居中对齐并均匀隔开.section1and .section2 divs
  • 添加display: flex;.bottom. 这将使.bottom扩展以适应可用空间
  • 更改flex: 1;flex: 1 0 auto;on .bottom。当窗口的高度很小时,这将停止.bottom减小尺寸

body,
html {
  margin: 0;
  padding: 0;
  height: 100%;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 4;
  display: flex;
  background: wheat;
  align-items: center;
  justify-content: center;
}

.bottom {
  /*Change*/
  flex: 1 0 auto;
  background: teal;
  /*Add*/
  display: flex;
}

.bottom_content {
  display: flex;
  flex-direction: column;
  /*Add*/
  align-items: center;
  justify-content: space-evenly;
}

.section1 {
  /*Remove*/
  /*flex:1;*/
  font-size: 20px;
  text-align: center;
}

.section2 {
  /*Remove*/
  /*flex:1;*/
}

.btn {
  background: red;
  color: white;
  padding: 20px;
}
<div class="container">
  <div class="top">
    <span>TOP CONTENT</span>
  </div>
  <div class="bottom">
    <div class="bottom_content">
      <div class="section1">
        <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacus quam, blandit non lacus in, venenatis tempor dolor. Aliquam in lectus lacus. </span>
      </div>
      <div class="section2">
        <div class="btn">
          THIS IS A BUTTON
        </div>
      </div>
    </div>
  </div>
</div>


推荐阅读