DIV 讓數字水平垂直置中?

.unsolve
{
    position: absolute;
    right: 10px;
    top:50%;
    transform: translate(0,-50%);
    z-index: 1;
    font-size: 13px;
    background-color: red;
    border-radius: 50%;
    color:#fff;
    width: 15px;
    height: 15px;
    padding: 5px;
    text-align: center;
}

<div class="unsolve">12</div>

這樣設定的時候,數字都會中間偏下,沒辦法完全中間。
請問該怎麼讓他完全水平垂直置中?

clipboard.png

阅读 5.3k
7 个回答

clipboard.png

.unsolve
    {
        position: absolute;
        right: 10px;
        top:0;
        bottom: 0;
        margin:auto;
        z-index: 1;
        font-size: 13px;
        background-color: red;
        border-radius: 50%;
        color:#fff;
        width: 15px;
        height: 15px;
        line-height: 15px;
        padding:5px;
        text-align: center;
        
    }

不用这么麻烦
单行文字
将行高 line-height 和 height 设为相等即可
多行文字
需要将文字抱在p标签中
外层div display:table 内层p display:table-cell

text-align:center; + line-height:容器元素高度

既然你都设置 height 了,那就直接设置 line-height

**设置一下行高就好了 transform: translate(0,-50%)
这句 可以 删除**

单行的垂直居中 使用line-height 即可。

新手上路,请多包涵

div中单行文字垂直居中,设置line-height和height两个属性,且两者值相同即可实现。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏