3列固定标题,可扩展高度以适合内容

时间:2018-08-20 05:19:06

标签: html css

我正在尝试在页面顶部创建一个包含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是我的小提琴的链接。

2 个答案:

答案 0 :(得分:5)

我建议使用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>

答案 1 :(得分:1)

您可以仅用8行完成上述操作,而不是编写的CSS。您只需要编写以下内容:

.header{
  display:flex;
}

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

,您可以添加以下类来检查是否一切都符合您计划做的事情:

*{
  border: 1px solid red;
}

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

在以下堆栈溢出代码段中检查结果:

* {
  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>

相关问题