2009-06-28 177 views
6

我想添加一個位於邊界頂部的圖標,將它分成兩半。css背景圖像定位(負位置?)

這是我到目前爲止有:

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
    <title>Untitled Document</title> 
    <style type="text/css"> 
     body { 
      background-color:#26140C; 
     } 

     .box { 
      width: 800px; 
      margin: 0 auto; 
      margin-top: 40px; 
      padding: 10px; 
      border: 3px solid #A5927C; 

      background-color: #3D2216; 
      background-image: url(Contents/img/icon_neutral.png); 
      background-repeat: no-repeat; 
      background-position:10px -20px; 
     } 
    </style> 
</head> 
<body> 
    <div class="box"> 
     <h1>This is a test!</h1> 
    </div> 
</body> 

相反的圖像是在邊境就像我希望,它在它之下。

回答

8

背景圖像在盒子內,因此將它移動到外面是不可行的。你可以做的是將你的圖像放在盒子外面並將其移動到其中。

你可以嘗試這樣的事情,這不是萬無一失,但可以讓你在那裏的一些方式。

<html> 
<head> 
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
     <title>Untitled Document</title> 
     <style type="text/css"> 
       body { 
         background-color:#26140C; 
       } 

       .box { 
         width: 800px; 
         margin: 0 auto; 
         margin-top: 40px; 
         padding: 10px; 
         border: 3px solid #A5927C; 

         background-color: #3D2216; 
       } 

       .image { 
        float: left; 
        position: relative; 
        top: -30px; 
       } 
     </style> 
</head> 
<body> 
     <div class="box"> 
      <img src='icon_neutral.png' class="image" /> 
       <h1>This is a test!</h1> 
     </div> 
</body> 
1
#box { 
    position:relative; 
} 
#shield { 
    width:41px; 
    height:41px; 
    position:absolute; 
    top:-25px; 
    left:25px; 
} 

<div id="box"> 

    <div id="shield"> 
    <img src="shield.png" /> 
    </div> 

    <h1>Site Title</h1> 

</div> 
12

另一種方法是使用僞類:你的盒子後,後注入的元素。

CSS

.box{ 
    position:relative; 
    } 
    .box:after{ 
     content:url(icon_neutral.png); 
     display:block; 
     position:relative; 
     top: -30px; 
    } 

HTML

<body> 
    <div class="box"> 
     <h1>This is a test!</h1> 
    </div> 
</body> 
+0

在某些情況下,這將打破現有的用戶界面,然後嘗試改變位置是「絕對」 – didxga 2014-05-14 03:15:36

5

只有使用CSS3另一種方式。

首先設置border-top: transparent,background-clip: border-box,然後負背景位置是可能的。

.box { 
    border-top: 8px solid transparent; 
    background-clip: border-box; 
    background-position: 0 -8px; 

    background-image: url(image.png); 
    background-repeat: repeat-x; 
    /* ... */ 
} 

另一種方式來獲得同樣的效果是通過添加額外的background-origin: border-box,然後背景負片位置不再需要。

.box { 
    border-top: 8px solid transparent; 
    background-clip: border-box; 
    background-origin: border-box; 
    background-position: 0 0px; 

    background-image: url(image.png); 
    background-repeat: repeat-x; 
    /* ... */ 
} 

更多信息:

http://www.css3.info/preview/background-origin-and-background-clip/