CSS 将 line-height 设置为相对于父元素的百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12686065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set line-height as a percentage relative to the parent element
提问by smilly92
I have a responsive element where it's width and height will both scale. Inside this I have some text which I want to center vertically.
我有一个响应元素,它的宽度和高度都可以缩放。在这个里面我有一些我想垂直居中的文本。
How can I set the text's line-height
to be the same as it's parent if I don't know the parent's height?
line-height
如果我不知道父母的身高,如何将文本设置为与其父母相同?
line-height: 100%
is relative to the font's regular height so this doesn't help...
line-height: 100%
相对于字体的常规高度,所以这无济于事......
回答by Mr. 14
Here's another way to center an element vertically. I came across this techniquesome time ago. Basically it uses a pseudo element and vertical-align: middle.
这是垂直居中元素的另一种方法。前段时间我遇到了这种技术。基本上它使用一个伪元素和 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;
}
回答by bjarkig82
回答by c_kick
I'd try putting the text inside another element, of which you know (or set) the size. Then setting relative positioning to it, top, left 50% and negative left and right margins.
我会尝试将文本放在另一个元素中,您知道(或设置)其大小。然后为其设置相对定位,顶部、左侧 50% 和负左右边距。
The only problem is that this relies on a known/fixed textblock. If the text is variable, I'm afraid you will have to resort to using Javascript..
唯一的问题是这依赖于已知/固定的文本块。如果文本是可变的,恐怕您将不得不求助于使用 Javascript..
回答by D. Dan
Regarding hyperlinks:
关于超链接:
I was having this problem regarding links in main menu. And since it was <a>
in <li>
tags I needed some surface for the links to be clickable/touchable(see touch target size).
So what I did was for the <ul>
I set a fixed height(through it's parent in this case), the <li>
-s are a percentage of it and the <a>
-s have a min-height and line-height properties set to them and it's easy from there to set the top. The code:
我遇到了有关主菜单中链接的问题。由于它<a>
在<li>
标签中,我需要一些表面才能使链接可点击/可触摸(请参阅触摸目标大小)。所以我所做的是为<ul>
我设置了一个固定的高度(在这种情况下通过它的父级),- <li>
s 是它的百分比,<a>
-s 为它们设置了 min-height 和 line-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; } }