3

考虑这个小提琴:http: //jsfiddle.net/qkAJD/

HTML

<div style="width:500px;">
     <h1 class="success-header" title="Success!">Success!</h1>
</div>

CSS

body {
    background: gray;
    margin:0;
}
.success-header {
    color: green;
    display: inline-block;
    font-size: 50px;
    height: 50px;
    margin: 0;
}
.success-header:before {
    content: attr(title);
    position:absolute;
    color:rgba(255, 255, 255, 0.3);
    top:1px;
    left:1px;
}

结果

问题

我们如何才能让<h1>标签在其容器中居中,并且仍然保持凸版效果?假设我们事先并不知道容器的宽度是 500px。也就是说,硬编码标题位置的解决方案是不可接受的。将标题居中很容易:

<div style="width:500px;text-align:center">
     <h1 class="success-header" title="Success!">Success!</h1>
</div>

但这破坏了凸版效果:

4

2 回答 2

3

“影子”相对于其最近的合格父级绝对定位。您可以通过添加来使直系父母符合条件position:relative

示例:http: //jsfiddle.net/qkAJD/5/

.success-header {
    color: green;
    display: inline-block;
    font-size: 50px;
    height: 50px;
    margin: 0;
    position: relative; /* changed line */
}

绝对 - 不要为元素留出空间。相反,将其定位在相对于其最近定位的祖先或包含块的指定位置。

来源,强调我的。

于 2013-08-27T21:15:56.280 回答
2

只需添加positon: relative.success-header因为您已经绝对定位了阴影。

.success-header {
    ...
    position: relative;
}

JSFiddle 示例。

于 2013-08-27T21:15:26.433 回答