【问题标题】:Vertically center only one of the divs within a parent div using fluid layout使用流体布局仅将父 div 中的一个 div 垂直居中
【发布时间】:2012-09-22 00:24:06
【问题描述】:

我试图在流畅的布局中使文本元素居中,这意味着<div> 的大小不固定。

我找到了一个非常好的解决方案,可以将子 <div> 在父 <div> 中水平和垂直居中,它的工作原理是:fiddle。 (原文来自the second method of this post

但是,如小提琴所示,Large Text 元素并不完全垂直定位在父<div class="block"> 的中心,而是整个子<div class="centered"> 居中。

我尝试将两个文本元素分成两个单独的<div>s,并将仅包含Large Text 元素的一个居中。但是,它不起作用,因为包含 small text 的第二个 <div> 被推出父 <div class="block">

那么我应该如何修改当前的居中解决方案,以使Large Text 元素在父<div class="block"> 内准确居中,同时仍包含small text 元素,就在Large Text 元素下方?

【问题讨论】:

    标签: html css centering fluid-layout


    【解决方案1】:

    vertican-align 被引入 CSS 以替代表格的valign HTML 属性。您会注意到display:inline-block; 不会创建表格单元格,并且根本不会以vertical-align 为中心。如果您不太关心display:table,在子级上使用display:table-cell

    除了上述之外,没有快速简便的方法可以在父母中居中。但是,如果您知道元素的高度,则可以使用 div 上的旧图像放置技巧。

    <div>
        <p>Centred Text, Horizontal and Vertical</p>
    </div>
    

    还有 CSS

    div {
        positon:relative;
        text-align:center;
        height:400px;
    }
    
    div p {
        position:relative;
        display:inline-block;
        height:30px;
        margin-top:-15px;
        top:50%;
        background-color:#cccccc;
    }
    

    Fiddle example

    如果这对您不起作用,您也可以绝对定位 &lt;p&gt;,尽管您需要在没有 text-align:center 在父级和 display:inline-block 帮助的情况下将其水平居中孩子。

    【讨论】:

      【解决方案2】:

      如果您仍在寻找这个问题的答案,我制作了一个演示: http://dabblet.com/gist/3762377

      当然,您必须为大文本(我的演示中的“.title”)提供固定高度。 然后使用负边距将 .box 向上拉,其值等于 .title 的高度。

      标记是:

      <div class="container">
      
          <div class="box">
              <h1 class="title">Title</h1>
              <p>Some text</p>
          </div>
      
      </div>
      

      CSS:

      .container {
          display: inline-block;      
          text-align: center;
          }
          .container:before {
              content: '';
              height: 100%;
              display: inline-block;
              vertical-align: middle;
              margin-right: -4px;
              }
      
          .box {
              display: inline-block;
              vertical-align: middle;
              width: 400px;
              margin-top: 70px; /* Height of .title. In this case .title's line-height. */
              }
          .title {
              display: block;
              margin: 0;
              padding: 0;     
      
              line-height: 70px;/* This property could be either height or top,bottom padding. */ 
              }       
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2016-05-25
        • 1970-01-01
        • 2014-02-15
        相关资源
        最近更新 更多