2013-05-05 208 views
2

在我的示例http://jsfiddle.net/cXbMb/中,我需要完整顯示徽標圖像,即標題圖像必須部分透支。還有下一個要求:標題圖像必須在標題下方5px開始。CSS:在子背景圖像上顯示父級背景圖像

<!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; 
} 
+0

聽起來像你需要'z-index'。 – Spudley 2013-05-05 20:40:50

回答

2

爲了解決它在你勾勒你應該創建標誌作爲自己的元素的方式,使用的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

我認爲要讓徽標圖像顯示在標題頂部的唯一方法是將其移出到另一個子元素。你不需要額外的標記 - 你可以只使用: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; 
}