[英]CSS - vertical align text and button
我在这里有一个jsfiddle- https ://jsfiddle.net/hjq6ay60/12/
超级简单,我总是忘记该怎么做。
我的文本向左浮动,按钮向右浮动。
我只需要将它们垂直居中-我确定您可以通过在文本中添加填充来做到这一点。
.block{
border: 1px solid red;
padding: 10px;
width: 400px;
&-top{
display: inline-block;
float: left;
vertical-align: middle;
}
&-bottom{
float: right;
vertical-align: middle;
&__button{
border: 1px solid grey;
height: 50px;
width: 50px;
}
}
}
为什么不使用display:table
和display:table-cell
? 看这里
.block {
display:table;
}
.block-bottom,.block-top {
display table-cell;
vertical-align: middle;
}
.block-bottom {
width: 50px;
}
并从.block-bottom .block-top
删除float:left
和float:right
我们可以通过以下方式利用position
和translateY
:
.block {
border: 1px solid red;
padding: 10px;
width: 400px;
position: relative; // Add here
&-top {
position: absolute; // Add here
top: 50%; // Add here
left: 5px; // Add here
right: 65px; // Add here
transform: translateY(-50%); // Add here
p {
margin: 0;
}
}
}
预习
一行: https : //jsfiddle.net/xpgszmvn/
多行: https : //jsfiddle.net/zqxvwv8L/
Flexbox可以免费为您做到这一点。 另外,您还能获得摆脱浮动的额外奖励。
.block{
border: 1px solid red;
padding: 10px;
width: 400px;
display: flex; align-items: center; /* Magic! */
&-top{
flex: 1; /* Stretch this item all the way */
/* By default, items take only as much as they need */
}
&-bottom{
/* No need for floats or display: */
&__button{
border: 1px solid grey;
height: 50px;
width: 50px;
}
}
}
例如,以相同的值使用height
和line-height
button{
height:30px;
line-height:30px;
text-align:center;
}
文字始终会居中
对于两行文字
button{
width:50px;
height:auto;
padding:10px;
}
这将创建高度取决于文本的按钮
试试这个,一定为您工作。
.block {
display: table
}
.block-top {
display: table-cell;
vertical-align: middle;
}
.block-bottom {
display: table-cell;
width: 50px;
vertical-align: middle;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.