2012-10-02 78 views
36

我有一个响应元素,它的宽度和高度都会缩放。在这里面我有一些我想垂直居中的文字。将行高设置为相对于父元素的百分比

如果我不知道父母的身高,我如何设置文字的line-height与父母相同?

line-height: 100%是相对于字体的常规高度,这不利于...

+0

是不是'em'单位类型用于这些情况? –

+6

我怀疑你可以实现这个没有JS – lanzz

+3

唉,'em'只会缩放相对于字体大小,而不是父元素的尺寸 –

回答

75

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

.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; 
} 
+1

这确实很聪明,很好! –

+2

非常酷的黑客! – smilledge

+3

你也应该发布html代码。 – matteo

1

我会尝试把文本另一种元素,而你只知道(或设置)的尺寸内。然后设置它的相对位置,顶部,左侧50%和左侧和右侧边距。

See this Fiddle

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

0

关于超链接:

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

.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; } } 
相关问题