【问题标题】:adding a heading to a section that uses display:table and display:table-cell向使用 display:table 和 display:table-cell 的部分添加标题
【发布时间】:2015-06-11 14:07:41
【问题描述】:

我在显示表格时遇到了一些困难。我通常在部分中使用display:tabledisplay:table-cell。特别是当我只想将部分的内容垂直居中时。可以这么说,我有以下 HTML:

<div class="wrapper">
  <div class="cell">
    <div class="red">

    </div>
  </div>
</div>

并将以下css应用于html:

html,body {
  height: 100%;
}
.wrapper {
  display: table;
  width: 100%;
  height: 100%;
}
.wrapper * {
  width: 100%;
  height: 100%;
}
.cell {
  display: table-cell;
  vertical-align: middle;
}
.red {
  margin-right: auto;
  margin-left: auto;
  background: red;
  height: 200px;
  width: 200px;
}

现在有一个小问题。我想为这个特定的部分添加一个节头,并且节头必须是.wrapper 的子级,因此 HTML 更改如下:

<div class="wrapper">

  <div class="section-heading">
    <h1>section heading</h1>
  </div>

  <div class="cell">
    <div class="red">

    </div>
  </div>

</div>

现在使用 display table 和 table-cell 的问题是,当我向部分添加标题时,我无法添加它而不影响 .wrapper 的其他子元素。那么如何添加标题(当在上面的 HTML 中添加标题时,.cell div 似乎会稍微水平移动)?

当然我可以使用绝对定位,但我只是想知道,有没有什么办法可以做到,而不需要将标题元素从流中取出?

FIDDLE HERE

【问题讨论】:

    标签: html css


    【解决方案1】:

    您是否尝试将 display:table-row 添加到部分标题?

    .wrapper > .section-heading{
        display:table-row;
        height:auto;
    }
    

    小提琴:http://jsfiddle.net/7xo353hg/4/

    【讨论】:

      【解决方案2】:

      您可以制作标题容器display: table-row:

      .section-heading {
          display: table-row;
          text-align: center;
      }
      

      查看演示:

      html, body {
          height: 100%;
      }
      .wrapper {
          display: table;
          width: 100%;
          height: 100%;
      }
      .wrapper * {
          width: 100%;
          height: 100%;
      }
      .cell {
          display: table-cell;
          vertical-align: middle;
      }
      .red {
          margin-right: auto;
          margin-left: auto;
          background: red;
          height: 200px;
          width: 200px;
      }
      
      .section-heading {
          display: table-row;
          text-align: center;
      }
      <div class="wrapper">
          <div class="section-heading">
              <h1>section heading</h1>
          </div>
          <div class="cell">
              <div class="red"></div>
          </div>
      </div>

      【讨论】:

      • 但是看看.cell 不再是.wrapper 的中心,这正是我想要的,我认为你的演示是我能得到的最接近的,所以我可能不得不去绝对位置本身具有cellwrapper 的垂直中心是我的主要目标。不过谢谢!
      • 我的意思是.red 不是.cell
      • 实际上 gopalraju 发现了这一点:您还需要添加 height:auto;
      • 另一种方法是使用position: absolute 作为标题,但没有topleft 值:jsfiddle.net/7xo353hg/5
      • 没问题,虽然技术上我先回答了(早 12 秒),干杯:D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多