【问题标题】:3 column fixed header that expands height to fit content3 列固定标题,可扩展高度以适应内容
【发布时间】:2018-08-20 05:19:06
【问题描述】:

我正在尝试在我的页面顶部创建一个具有 3 个“列”的固定标题。第一个在左侧左对齐,第二个相对于整个页面居中 - 与其他两个列大小无关,第三个右对齐,卡在右侧。我希望所有内容都垂直居中。

浮动并没有真正起作用,因为中间列没有正确居中。所以我用了左右两个position: absolute div,中间只留了一个div。

我的问题是我无法让标题扩展以包含更高的左侧 div,并且我无法让内容垂直居中。

我做错了什么?谢谢!

这是我的代码:

.header {
  z-index: 8;
  top: 0;
  left: 0;
  position: fixed;
  padding-top: 1rem;
  padding-bottom: 1rem;
  width: 100%;
  background: white;
  z-index: 8;
  border-bottom: 1px solid black;
  text-align: center;
}

.left {
  position: absolute;
  top: 1rem;
  left: 1rem;
  border: 1px solid gray;
  background: red;
  padding: 1rem;
  height: 10rem;
}

.right {
  position: absolute;
  right: 1rem;
  top: 1rem;
  background: yellow;
  border: 1px solid gray;
}

.middle {
  background: green;
  border: 1px solid gray;
}
<div class="header">
  <div class="left">Left</div>
  <div class="middle">MIDDLE......</div>
  <div class="right">Right</div>
</div>

Here 是我的小提琴的链接。

【问题讨论】:

    标签: html css


    【解决方案1】:

    我建议使用 flexbox 进行垂直对齐。

    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    header>div {
      padding: 1rem; /* To improve visibility */
      width: calc(100% / 3);
    }
    
    .col1 {
      text-align: left;
    }
    
    .col2 {
      text-align: center;
    }
    
    .col3 {
      text-align: right;
    }
    <header>
      <div class="col1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
      <div class="col2">Lorem ipsum dolor sit amet, consectetur adipiscing elit...</div>
      <div class="col3">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    </header>

    【讨论】:

      【解决方案2】:

      除了您编写的 css 之外,您只需 8 行即可完成上述操作。您只需要编写以下内容:

      .header{
        display:flex;
      }
      
      .left, .middle, .right{
        width: calc(100% / 3);
        text-align:center;
      }
      

      您可以添加以下类来检查是否一切都按照您的计划进行:

      *{
        border: 1px solid red;
      }
      

      Here 是显示上述代码结果的小提琴的链接。

      在下面的栈溢出sn-p中检查结果:

      * {
        border: 1px solid red;
      }
      
      .header {
        display: flex;
      }
      
      .left,
      .middle,
      .right {
        width: calc(100% / 3);
        text-align: center;
      }
      <div class="header">
        <div class="left">Left</div>
        <div class="middle">MIDDLE......</div>
        <div class="right">Right</div>
      </div>

      【讨论】:

        猜你喜欢
        • 2014-05-10
        • 1970-01-01
        • 2012-02-11
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        相关资源
        最近更新 更多