簡體   English   中英

背景圖像中心和調整大小

[英]Background image center and resize

我正在為客戶開發一個網站,其中有一個背景圖片,該圖片將以頁面為中心,並覆蓋有文本、鏈接等。

我目前將圖像大小調整如下:

img.bg
   {
   height:100%;
   position:absolute;
   }

這使圖像適合瀏覽器的高度,但將其與左側對齊。 我需要它居中。

由於我需要它有條件地響應瀏覽器高度的變化,因此通常的居中技巧不起作用。

謝謝!

答案取決於你所追求的。

如果您想在網站背景中顯示圖像(我想您是在說),那么我不確定您使用的是什么方法,但如果您在 html 和 css 中img.bg{} ,以及只需將以下內容放入您的 CSS 您將得到您想要的...

body{
    background-image:url('background.gif'); // substitute background.gif for the correct file path
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center;
    background-size:auto 100%;
}

嘗試刪除“位置:絕對”並添加邊距:0 自動。 例如:

img.bg
{
   height:100%;
   margin: 0 auto;
}

或者可能只是將它放在一個表格中<table align="center"> <tr><td>"image goes here"</td></tr>它更容易管理,因為您可以在網頁中添加更多項目未來毫無困難,添加邊框,更改表格顏色等。

我可以想到 go 的幾種方法(未經測試,因此您可能需要調整):

img.bg {
   position: absolute;
   /* Top and/or bottom for stretching it vertically as needed. Setting both will likely make it the size of the whole body, so beware. Remove bottom to keep it from doing that if necessary. */
   top: 0;
   bottom: 0;
   /* Left and/or right for sizing/positioning */
   left: 25%; /* Percentage position will make it adjust to browser window size, exact percent may need to be tweaked to get right and will depend on the image's size. */
}


img.bg {
   display: block;
   height: 100%;
   width: 500px; /* Whatever your desired width is. */
   margin: 0 auto; /* This should work as long as width is set. */
}

根據您的具體設計,其中任何一個都應該可以工作並且可以響應瀏覽器 window 的大小。 第二個可能是最靈活和最容易實現的,因為您不必擺弄定位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM