通过CSS在图像上水平居中文本

Zau*_*bov 22 html css image alignment

考虑以下html:

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       Text of variable length
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

哪里:

.image {
    position:relative;
    text-align:center; // doesn't work as desired :(
}

.text {
    position:absolute;
    top:30px;
}
Run Code Online (Sandbox Code Playgroud)

如果有办法在.imagediv 的中心水平对齐文本,你能告诉我吗?我不能使用该left属性,因为文本的长度是未知的,text-align属性不适用于.textdiv :(

谢谢.

Dam*_*ric 58

尝试以下CSS:

.image {
    position:relative;
}

.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 30px;
    width: 100%
}
Run Code Online (Sandbox Code Playgroud)

  • 将`float:left`添加到`.image`,这就是答案:http://jsfiddle.net/chvYu/ (4认同)

Pur*_* Sh 9

尝试这个:

.image {

    position:relative;
}

.text {
    width:100%;    
    height:100%;
    position: absolute;
    top: 0;
    left: 0px;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    display: flex;
}
Run Code Online (Sandbox Code Playgroud)