[英]In HTML/CSS, can you repeat an image in the foreground, like you can in the background?
這是我的CSS
.test {
background-image:url('images/smiley.gif');
background-repeat:repeat;
}
這是我的HTML:
<div class="test" id="xyz">some code which should come background to image</div>
我寫的代碼設置了背景圖像。
但我想在文本的頂部放置一個圖像,而不是在它后面,以便它覆蓋文本。 (我也希望它自動重復填充元素,可以是任何大小。)
我怎樣才能做到這一點?
這應該可以解決問題。 :before
選擇器創建一個帶有給定content
的假div
:before
(這里是一個空格,因為沒有content屬性,我認為使用空字符串內容,不會創建假div
),並且可以設置樣式。 因此創建假div
,並使用background-image
,給定height
和width
以及z-index
為1
樣式設置,而真實div
的z-index為零,並顯示在下方。
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
.test:before {
content: " ";
position: absolute;
width: 100px; height: 100px;
background-image:url('http://upload.wikimedia.org/wikipedia/commons/a/a4/Smiley_transparent.png');
background-repeat:repeat;
z-index: 1;
}
.test {
z-index: 0;
}
</style>
</head>
<body>
<div class="test" id="xyz">some code which should come background to image</div>
</body>
</html>
將此與Paul D. Waite的回答相結合,可以避免在代碼中有明確的跨度。
我認為:before
必須應用於.test :first-child:before
,所以它將是xyz
div
一個孩子,而不是兄弟姐妹,但似乎沒有必要(盡管它讓我逃脫了原因) 。
你可以在jsfiddle上測試結果。
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
.test {
position: relative;
}
.test:before {
content: " ";
position: absolute;
top: 0;
bottom: 0;
height: auto;
left: 0;
right: 0;
width: auto;
background-image:url('http://upload.wikimedia.org/wikipedia/commons/a/a4/Smiley_transparent.png');
background-repeat:repeat;
}
</style>
</head>
<body>
Some text before.
<div class="test" id="xyz">some code which should come background to image</div>
Some text after.
</body>
</html>
有趣的任務。 如果您願意添加額外的HTML元素,我認為應該這樣做。 (或者,使用.test:before
而不是.test .foregroundImage
,就像在Georges的回答中一樣 )。
<div class="test" id="xyz"><span class="foregroundImage"></span>some code which should come background to image</div>
.test {
position: relative;
}
.test .foregroundImage {
position: absolute;
top: 0;
bottom: 0;
height: auto;
left: 0;
right: 0;
width: auto;
background-image:url('images/smiley.gif');
background-repeat:repeat;
}
有關工作示例,請參見http://jsfiddle.net/RUJYf/ 。
CSS
<style type="text/css">
.test { position: relative; }
.test img, .test p { position: absolute; top: 0; }
.test img { z-index: 10; }
.test p { margin: 0; padding: 0; }
</style>
HTML
<div class="test">
<img src="images/smiley.gif" />
<p>some code which should come background to image</p>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.