在不知道span标签的高度之前怎么让span内的文字垂直居中?

尝试用vertical-align:middle,line-height:50%,但是不行

html代码:
<div id="cliBtn">

<a href="#" class="aItems top"><span>top</span></a>
<a href="#" class="aItems right"><span>right</span></a>
<a href="#" class="aItems left"><span>left</span></a>
<a href="#" class="aItems bottom"><span>bottom</span></a>

</div>

css代码:

cliBtn{

width: 100%;
background: #ccc;
margin: 1rem auto;
position: relative;

}

cliBtn:after{

content: '';
display: block;
padding-bottom:100%;

}

cliBtn a{

position: absolute;
width: 50%;
height: 50%;
box-sizing: border-box;
border: 1px solid #333;

}

cliBtn a:nth-child(1){

top:0;
left:0;
border-top-left-radius: 100%;

}

cliBtn a:nth-child(2){

top:0;
left:50%;
border-top-right-radius: 100%;

}

cliBtn a:nth-child(3){

top:50%;
left:0;
border-bottom-left-radius: 100%;

}

cliBtn a:nth-child(4){

top:50%;
left: 50%;
border-bottom-right-radius: 100%;

}

cliBtn a:nth-child(2n){

background: #ffff99;

}

cliBtn a span{

display: block;
width:100%;
height: 100%;
text-align: center;
vertical-align: middle;
line-height: 100%;

}
效果图:

clipboard.png

阅读 8k
2 个回答

在 #cliBtn a 下加上 display: table;
在 #cliBtn a span 下加上 display: table-cell; 去掉 display:block; 应该就可以了

首先 vertical-middle只会作用于inline和inline-block元素中,另外你的外层的height和line-height都是百分比值,vertical-middle是不起作用的。如果不考虑兼容性的话可以尝试用flex布局解决这个问题。

#cliBtn a {
    display: flex;
    align-items: center;
    position: absolute;
    width: 50%;
    height: 50%;
    box-sizing: border-box;
    border: 1px solid #333;
}
#cliBtn a span {
    display: block;
    width: 100%;
    text-align: center;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题