2016-04-05 146 views
-1

enter image description here 請看附加的圖像來查看問題。 無論瀏覽器窗口大小如何,我都希望圖像保持居中位置,以保持其下方的矩形。 當我調整瀏覽器的大小時,圖像不會保留與其下面的矩形有關的寬高比。 如何讓圖像的大小相對於它下面的矩形調整大小? 我試過尋找網絡,但什麼也沒找到。Css響應圖像問題

body{ 
 
\t background-color: #fcab55; 
 
} 
 

 
* { 
 
    box-sizing: border-box; 
 
} 
 

 
.container{ 
 
\t width: 900px; 
 
\t height: auto; 
 
\t margin-left: auto; 
 
\t margin-right: auto; 
 
\t border: 1px slid red; 
 
\t max-width: 100%; 
 
} 
 

 

 

 
.pizza_img_background{ 
 
\t max-width: 100%; 
 
\t width: 900px; 
 
\t height: 225px; 
 
\t background-color: #010606; 
 
\t margin-left: auto; 
 
\t margin-right: auto; 
 
} 
 

 
.pizza{ 
 
\t position: relative; 
 
\t max-width: 100%; 
 
\t width: 855px; 
 
\t height: 192px; 
 
\t margin-top: 15px; 
 
\t margin-left: 22.5px; 
 
\t margin-right: 22.5px; 
 
\t background-image: url("images/pizza.png"); 
 
\t background-repeat: no-repeat; 
 
\t background-size: contain; 
 
}
\t \t <body> 
 
\t \t \t <header> 
 
\t \t \t </header> 
 
\t \t <div class="container"> 
 
\t \t \t <div class="pizza_img_background"> 
 
\t \t \t \t <img src="images/pizza.png" alt="Pizza " class="pizza"> 
 
\t \t \t </div> 
 

 
\t \t </div> 
 

 
\t \t </body>

+0

有什麼理由你設置它爲背景圖像,而不是僅僅使用'img'元素? – APAD1

+0

...以及爲什麼「下方的矩形」不只是一個簡單的邊框或箱形陰影? – CBroe

+0

您是否嘗試將'.pizza'的寬度和高度設置爲'100%'而不是固定寬度? –

回答

0

嘗試改變

margin-left: 22.5px; 
margin-right: 22.5px; 
width: 855px; 

padding-left: 22.5px; 
padding-right: 22.5px; 
width: 100%; 

這裏是一個例子codepen http://codepen.io/anon/pen/qZVKdJ

我希望這能幫到你

+0

非常感謝。這正是我所期待的。我從你的代碼中改變的唯一東西就是高度。我不希望身高改變。再次感謝。 –

2

你的問題很不清楚,這是你在找什麼?

.pizza { 
 
    text-align:center; 
 
} 
 
.img-container { 
 
    display:inline-block; 
 
    background:#000; 
 
    padding:20px; 
 
} 
 
    .img-container:hover { 
 
    background:#ccc; 
 
    } 
 
    .img-container img { 
 
    max-width:100%; 
 
    }
<div class="pizza"> 
 
    <div class="img-container"> 
 
    <img src="http://lorempizza.com/640/480" alt="Pizza" /> 
 
    </div> 
 
</div>

+0

居住在瀏覽器窗口時出現問題。圖像沒有保持與矩形下方的寬高比。我有一個圖像白色披薩和一個Css矩形下... –

+0

工作對我來說很好。 – APAD1

+0

你也是對的。謝謝!祝大家度過愉快的一天。 –