我有这个:
.class {
height:10px;
padding:2px;
box-sizing:border-box;
}
.class .subclass {
height:100%;
line-height:???;
}
如您所见,class
具有固定高度,但 subclass
具有相对百分比高度。尽管该高度的值为 100%
,但它并不等于父级的高度,因为它受到父级的 padding
属性的影响。我需要的是将 line-height
属性设置为等于 height
属性,以便使文本垂直居中。
问题:
如何使用 LESS 获取当前类(我们正在设置 line-height
属性的类)高度?
我知道我可以设置变量然后进行计算,这样:
@class-height:10px;
@class-padding:2px;
@subclass-height:calc(@class-height - @class-padding * 2); //*2 because of Top & bottom padding
.class {
height:@class-height;
padding:@class-padding;
box-sizing:border-box;
}
.class .subclass {
height:@subclass-height;
line-height:@subclass-height;
}
但我想知道是否有一种简单的方法可以实现这一点,无需计算和设置固定变量。
最佳答案
如果父高度是固定数字,则可以使用绝对定位。
.parent{
height: 100px;
background-color: tomato;
width: 100%;
}
.child{
position: relative;
left: 0;
right: 0;
margin: 0 auto;
top: 50%;
transform: translateY(-50%);
text-align: center;
}
另一个选择是利用table
的vertical-align属性,这样你就可以像这样编写你的CSS。
.parent{
height: 100px;
background-color: tomato;
width: 100%;
display: table;
text-align: center;
}
.child{
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
关于CSS Less - 获取当前类的高度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37209700/