【问题标题】:Set line-height as a percentage relative to the parent element将 line-height 设置为相对于父元素的百分比
【发布时间】:2020-09-03 15:32:12
【问题描述】:

我有一个响应式元素,它的宽度和高度都会缩放。在这里面我有一些我想垂直居中的文本。

如果我不知道父级的身高,如何将文本的line-height 设置为与其父级相同?

line-height: 100% 是相对于字体的常规高度,所以这无济于事......

【问题讨论】:

  • 不是em 单位类型用于这些情况吗?
  • 我怀疑你可以在没有 JS 的情况下实现这一目标
  • 唉,em 只会相对于字体大小而不是父元素尺寸进行缩放
  • 提供您的实际代码肯定会帮助我们提供具体案例的答案

标签: css


【解决方案1】:

这是另一种垂直居中元素的方法。前段时间我遇到了this technique。基本上它使用伪元素和垂直对齐:中间。

.block::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

【讨论】:

    【解决方案2】:

    既然已经是 2019 年了,你也可以使用 flexbox 来实现这一点:)

    为此,请将以下类添加到父元素:

    display: flex;
    flex-direction: column;
    justify-content: center;
    

    看到这个Fiddle

    【讨论】:

    • 自从 2019 年以来,人们仍在使用 IE,不幸的是,这不适用于 IE 的所有条件。
    • 不要听反对者的意见。任何使用 IE 的人都应该期望 2019 年的互联网看起来像垃圾。
    • 由于这是 Web 开发,您应该为没有 flexbox 的使用提供某种优雅的降级。完全同意它在视觉上看起来像垃圾,但它仍应保持功能性、可用性和意义。
    【解决方案3】:

    我会尝试将文本放在您知道(或设置)大小的另一个元素中。然后设置它的相对定位,上、左50%和负左右边距。

    See this Fiddle

    唯一的问题是这依赖于已知/固定的文本块。如果文本是可变的,恐怕你将不得不求助于使用 Javascript..

    【讨论】:

      【解决方案4】:

      关于超链接:

      我在主菜单中的链接方面遇到了这个问题。由于它是<li> 标签中的<a>,因此我需要一些表面以使链接可点击/可触摸(请参阅touch target size)。 所以我为<ul> 设置了一个固定高度(在这种情况下通过它的父级),<li>-s 是它的百分比,<a>-s 有一个最小高度和行- height 属性设置为它们,从那里设置顶部很容易。代码:

      .menu-header-main-container{
      position: fixed;
      top: 0;
      bottom: 160px;
      }    
      .menu-header-main-container ul.menu {
                height: 100%; }
                .menu-header-main-container ul.menu li {
                  height: 33.33%;
                  max-height: 110px; }
                  .menu-header-main-container ul.menu li a {
                    line-height: 40px;
                    min-height: 40px;
                    top: calc(50% - 20px);
                    position: relative; } }
      

      【讨论】:

        【解决方案5】:

        您不能仅使用 CSS 将 line-height 设置为父元素高度的 100%。相反,您可以使用 CSS 将元素垂直居中。

        .parent {
           height:150px;
           position:relative;
           border:1px solid #FDD;
        }
        .position-center {
            position:absolute;
            top:50%;
            transform:translateY(-50%);
        }
        <div class="parent">
          <span class="position-center">I am vertically centered element</span>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-11
          • 2013-06-28
          • 1970-01-01
          • 2013-01-22
          • 2020-10-27
          相关资源
          最近更新 更多