2012-04-17 87 views
3

我想把圖像放在我的主頁的左側。我知道如何在HTML中做到這一點,但我想在CSS類中創建它。我不知道我需要做些什麼來解決它。我想要的圖片被稱爲Nobullying.jpg HTML:如何對齊CSS上的圖像?

<html> 
    <head> 
    <link rel="stylesheet" type="text/css" href="body.css"/> 
    </head> 
    <body> 
    <h1>Bully-Free Zone</h1> 
    <h2>"Online harassment has an off-line impact"</h2> 
    <!--Menu-->I 
    <div id="nav"> 
    <a href="mainpage.htm" class="nav-link">HOME</a> 
    <a href="page1.htm" class="nav-link">ASSISTANCE</a> 
    <a href="page2.htm" class="nav-link">CYBER-BULLYING SIGNS</a> 
    <a href="page3.htm" class="nav-link">REPORT</a> 
    </div> 
    <div id="picture"></div> 
    <!--Copyright--> 
    <div id="center"> 
    <td> Copyright © 2012 Bully-FreeZone.com</td> 
    </div> 

    </body> 
    </html> 

CSS類:

#picture{background-image:Nobullying.jpg; 
    width:40px; height:40px; 
    } 

這就是我想要的圖片。 (紅色框) http://imgur.com/Ef2Au

回答

6
#picture { 
background-image:url('no-bullying.jpg'); 
height:100px; 
width:50px; 
position: absolute; 
bottom:10px; 
left:10px; 
} 
+0

同時會有什麼我在我的HTML – Backtrack 2012-04-17 15:02:49

+0

?這不僅僅是多餘的,但如果由於填充或定位造成圖像不對齊,則會導致錯誤。另外,@Backtrack表示他們想要在CSS中完成圖像,而不是通過html。 – Moses 2012-04-17 15:37:20

0
#picture{ 
    background-image:url(Nobullying.jpg); 
    width:40px; height:40px; 
    float:left; 
    } 

我用ID這裏不是一類。圖像應該用ID =「圖片」來標識。

在CSS中,當你使用float時會有點棘手。如果你已經可以在html中做到這一點,只需使用html。否則,你將不得不學習一些額外的東西。

答案被更新

3

調整你的CSS像這樣:

#picture{ 
    background-image:url('/path/to/Nobullying.jpg'); 
    width:40px; height:40px; 
    position: absolute; /* this removes it from document flow */ 
    left: 5px; /* this places image 5px away from the leftmost area of the container */ 
       /* you can choose from left/right and top/bottom for positioning */ 
       /* play around with those and you should get a hang of how it works */ 
} 

記住:當你使用CSS背景圖像的路徑是從css文件的角度(而不是HTML文件中包含的CSS)。

所以,如果你的目錄結構就像

root 
--> css -> styles.css 
--> images -> Nobullying.jpg 
--> index.html 

那麼你的路徑可能是url('../images/Nobullying.jpg')或'URL( '/圖片/ Nobullying.jpg');

+0

我可以同時使用底部和頂部,因爲當我同時使用時它不工作。它只是頂部 – Backtrack 2012-04-17 15:30:22

+0

@Backtrack不,你不能結合底部和頂部;你也不能左右合併。但是你可以做左+底或右+頂。這裏有一篇很好的文章來理解CSS定位背後的原理:http://www.alistapart.com/articles/css-positioning-101/ – Moses 2012-04-17 15:33:47

2

或者您可以使用fixed定位來將其保持在該位置而不管滾動。

#picture{ 
    background: url(Nobullying.jpg) no-repeat; 
    width:40px; 
    height:40px; 

    position: fixed; 
    bottom:10px; 
    left:10px; 

}

也使用URL()和不重複的背景圖像。

+0

downvote有什麼用? – Greg 2012-04-17 15:09:44

+0

除非使用'background' [簡寫](http://www.dustindiaz.com/css-shorthand/),'no-repeat'需要與'background-repeat'規則分開使用。 – 2012-04-17 15:11:38

+0

已更新的答案。當你下次投票時添加評論,否則它沒用。 – Greg 2012-04-17 15:13:12

1

您的background-image規則中有語法錯誤。除此之外,你可以你爲什麼要同時使用``標籤和CSS`背景image`使用position:absolute來定位元素

#picture{ 
    background-image: url(Nobullying.jpg); 
    width:40px; 
    height:40px; 
    position:absolute; 
    left:10px; 
    bottom:10px; 
}