【问题标题】:Vertical align div to unknown height div without affecting horizontal centering垂直对齐 div 到未知高度 div 而不影响水平居中
【发布时间】:2018-01-25 23:49:29
【问题描述】:

在上图中,有一个 100% 宽度和未知高度的红色 div。高度由橙色 div 的高度加上一些填充来控制。

橙色 div 的高度和宽度由我们事先不知道的动态文本内容控制,但橙色 div 应该在红色 div 内水平居中,两边宽度相等。

蓝色 div 将具有固定的宽度和高度(比如说 50px x 50px,比橙色 div 小),并放置在左侧。它有时是可见的,有时是不可见的(由 javascript 控制 - 可见性或显示,以效果最好的为准),但在任何一种情况下,它都不应该影响橙色 div 的水平居中。但是,蓝色 div 的垂直中心应该垂直对齐以匹配橙色 div 的垂直中心。

我可以添加额外的 div,或将内容更改为跨度,诸如此类,但目前我尝试的任何事情都意味着橙色 div 的水平居中流在我需要蓝色 div 时考虑了蓝色 div div 完全脱离了流程。

有什么想法吗?

【问题讨论】:

    标签: css


    【解决方案1】:

    您应该使用display: flexalign-items,将最小高度传递给您的容器也很重要。

    我已经创建了一个快速小提琴来解释我从你那里了解到的内容。

    看看这个 (JSFiddle):

    .container {
      width: 300px;
      padding-bottom: 20px;
      padding-top: 20px;
      border: solid 1px red;
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 30px;
    }
    
    .inner {
      background: rgba(0, 0, 0, 0.5);
      width: 50%;
    }
    
    .fixed {
      position: fixed;
      left: 20px;
      border: solid 1px blue;
      height: 30px;
    }
    <div class="container">
      <div class="inner">
        Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum
      </div>
      <div class="fixed">
        fixed
      </div>
    </div>

    【讨论】:

    • 固定元素随 Chrome 上的窗口滚动。
    【解决方案2】:

    绝对定位蓝色 div 并使用 transform 使其居中。您需要在两个彩色 div 周围添加一个容器。

    .red {
      border: 2px solid red;
      width: 100%;
    }
    
    .container {
      position: relative;
    }
    
    .blue {
      background-color: blue;
      border: 2px solid darkblue;
      width: 70px;
      height: 70px;
      position: absolute;
      left: 40px;
      top: 50%;
      transform: translate(0, -50%);
    }
    
    .yellow {
      background-color: yellow;
      border: 2px solid goldenrod;
      margin: 10px auto 50px;
      width: 120px;
      height: 200px; /* change me */
    }
    <div class="red">
      <div class="container">
        <div class="blue">
        </div>
        <div class="yellow">
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2013-11-25
      相关资源
      最近更新 更多