CSS:在子背景图像上显示父背景图像

时间:2013-05-05 20:39:17

标签: css

在我的示例http://jsfiddle.net/cXbMb/中,我需要完全显示徽标图像,即标题图像必须部分透支。还有下一个要求:标题图像必须在标题下方开始5px。

<!DOCTYPE html>
<html><head></head>
<body>
    <header>
        <h1>Headline</h1>
        <div></div>
    </header>
</body>
</html>
body { padding: 0; margin: 0 auto; width: 400px; }
header {
    background-image: url('http://placehold.it/100x50/ffff00&text=LOGO');
    background-position: left top;
    background-repeat: no-repeat;
}
header h1 { text-align: right; margin: 0 0 5px; padding: 0; font-size: 1em; }
header div {
    background-image: url('http://placehold.it/400x100/0000ff&text=HEADER');
    background-position: left top;
    background-repeat: no-repeat;
    height:200px;
}

2 个答案:

答案 0 :(得分:3)

要按照您概述的方式解决它,您应该将徽标创建为自己的元素,并使用z-index。像这样:http://jsfiddle.net/fzUtb/1/

<!DOCTYPE html>
<body>
    <header>
        <div class="logo"></div>
        <h1>Headline</h1>
        <div></div>
    </header>
</body>

并且新样式如下:

header{position:relative;}
.logo { background-image: url('http://placehold.it/100x50/ffff00&text=LOGO'); background-position: left top; background-repeat: no-repeat;position:absolute;z-index:2;width:100px;height:50px; }

可能是分裂,但我建议徽标不是CSS图像! CSS是关于样式的,但这个标识是真实的内容,所以我认为语义上的HTML元素更有意义。这样它会打印(CSS背景不打印),它可以为屏幕阅读器和谷歌提供ALT文本!

答案 1 :(得分:1)

我认为,要让徽标图像显示在标题顶部的唯一方法是将其移动到另一个子元素中。您不需要额外的标记 - 您只需使用:after伪元素。

header {
    position:relative;
}
header:after {
    content:'';
    display:block;
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
    background-image: url('http://placehold.it/100x50/ffff00&text=LOGO');
    background-position: left top;
    background-repeat: no-repeat; 
}
相关问题