CSS如何使文本在背景图片中居中?

3

我有一个包含数字的背景图片。我无法将数字放在圆形的中心位置,目前我已经将数字居中了,但它在圆形的最上方。我该如何将其向下移动到中心位置?

HTML代码:

<div class="number">
  <p>
  576
  </p>
</div>

CSS 代码:

.number{
    float:left;
    background-position: center;
    text-align: center;
    font-size:200%; 
    }

.number p{  
    position:relative;
    top: 38%;
    left:57%;
    z-index:999;    
    background-image: url("http://davidwalsh.name/demo/css-circles.png");
    width: 207px;
    height: 204px;
    }

这里 是 jsfiddle

5个回答

2

只需为您的p元素设置一个line-height,例如line-height: 204px;,该值等于元素的高度。

演示

.number p {
    /* Other properties here */
    line-height: 204px; /* add this */
}

此外,我不知道为什么你在这里使用 topleft 属性以及 z-index 属性,我认为你可以通过简化它们来清理混乱。

如果段落包含多行,该怎么办? - Nilesh Mahajan
@NileshMahajan 这里不是那种情况... 我根据使用案例进行操作。 - Mr. Alien
是的,但你不认为这个解决方案应该始终具备可扩展性吗?我只是表达了我的想法... - Nilesh Mahajan

1

使用 line-height: 204px

当文本只有一行时,此选项适用。

.number{
 float:left;
 background-position: center;
 text-align: center;
 font-size:200%; 
 }
 
.number p{ 
 position:relative;
 top: 38%;
 left:57%;
 z-index:999; 
 background-image: url("http://davidwalsh.name/demo/css-circles.png");
 width: 207px;
 height: 204px;
    line-height: 204px;
 }
<div class="number">
 <p>
    576
    </p>
    </div>


1
请检查您的 Fiddler。https://jsfiddle.net/ydz8cn7b/1/ 我已根据您的要求进行了更新: HTML
<div class="number">
    <p>576</p>
</div>

CSS
.number {
    float:left;
    background-position: center;
    text-align: center;
    font-size:200%;
    display:table;
}
.number p {
    display:table-cell;
    background-image: url("http://davidwalsh.name/demo/css-circles.png");
    width: 207px;
    height: 204px;
    vertical-align:middle;
}

1
其中一个好的解决方案是:
display: table-cell;
vertical-align: middle;

请检查Fiddle


1
将以下CSS属性添加到这个类.number p{}中。
display: table-cell;
vertical-align: middle;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接