【问题标题】:Having trouble in vertically center aligning a div with block of texts将 div 与文本块垂直居中对齐时遇到问题
【发布时间】:2023-04-10 04:51:01
【问题描述】:

https://jsfiddle.net/n00q5wdn/

请参考 fiddle 的输出以及我正在链接图像以便更清楚地理解问题。

我只想让“hgroup”垂直居中。

HTML:

<article id="full-height">
    <div class="hgroup">
        <h1>Exotic Designs</h1>
        <h2>Best Quality</h2>
    </div>
</article>

SCSS:

#full-height {
  background-color: red;
  min-height: 600px;
}

.hgroup {
  h1 {
    color: white;
    font-size: 5em;
    font-weight: 800;
    line-height: 0.8em;
    text-shadow: black 0 0 20px;
    text-align: center;
  }
  h2 {
    display: block;
    color: white;
    width: 60%;
    max-width: 200px;
    margin: 0 auto;
    text-align: center;
    border: 1px solid white;
    margin-top: 15px;
    padding: 10px;
    background: rgba(0, 0, 0, 0.5);
    font-size: 1.3em;
  }
}

【问题讨论】:

    标签: css alignment vertical-alignment


    【解决方案1】:

    最适合这类问题的是 flexbox,它使用 Box Alignment 规范,专门针对这些情况创建。

    如果您将#full-height-元素设置为显示为弹性行容器,您可以将内容与align-items(垂直)和justify-content(水平)对齐。

    #full-height {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    

    forked fiddle here

    这适用于大多数现代浏览器,如果您通过 Autoprefixer 之类的工具运行它,您也可以在一些稍旧的浏览器(IE10、旧版 Safari 等)中运行它。 IE9 和其他古老的浏览器不支持 flexbox,所以我建议使用具有固定边距的 .hgroup 元素或仅顶部对齐等进行后备。如果您可以摆脱容器的固定、显式高度,还有另一个,更hacky和涉及的解决方案:

    我看到您已经尝试使用inline-blockvertical-align 尝试使用middle 关键字进行垂直居中。仅当您可以在 #full-height 容器上设置明确的高度并使用“ghost”元素强制行高计算覆盖框时,这才有效,例如:

    #full-height {
      height: 600px;
      text-align: center; /* horizontal centering */
    }
    /** 
    * "ghost element", to force the calculation of the
    * middle keyword to equal the vertical middle of
    * the box.
    */
    #full-height:before {
      content: '';
      display: inline-block;
      vertical-align: middle;
      height: 100%;
      /* offset the whitespace generated by inline-block.
         May vary with font-size. */
      margin: -.25em; 
    }
    
    .hgroup {
      display: inline-block;
      vertical-align: middle;
     }
    

    jsbin example for this solution here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-20
      • 2012-03-26
      • 2013-02-09
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      相关资源
      最近更新 更多