1. 程式人生 > >CSS——img自適應div大小

CSS——img自適應div大小

程式碼如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>哈哈</title>
        <style>
            .div1 {
                width: 300px;
                height: 100px;
                background: red;
            }
            .bg1{
/* 這種不會失真 */ max-height: 100%; max-width: 100%; } .div2 { width: 300px; height: 100px; background: blue; } .bg2{ /* 這種不會失真 */ min-height
: 80%; min-width: 80%; } .div3 { width: 300px; height: 100px; background: green; } .bg3{ /* 這種情況可能會失真 */ height: 50%; width: 50%; } </
style> </head> <body> <div class="div1"> <img class="bg1" src="img/qt_img/SA_4.png"/> </div> <div class="div2"> <img class="bg2" src="img/qt_img/SA_4.png"/> </div> <div class="div3"> <img class="bg3" src="img/qt_img/SA_4.png"/> </div> </body> </html>

執行結果:

注:

max-height(用來設定指定元素的最大高度):這個屬性會阻止 height 屬性的設定值變得比 max-height 更大。

min-height(用來設定指定元素的最小高度):這個屬性會阻止 height 屬性的設定值變得比 min-height 更小。 當 height 屬性設定的高度小於該屬性的值時,則 height 屬性會失效。

max-height 過載(覆蓋掉) height, 但是 min-height 又會過載(覆蓋掉) max-height。即min-height 會將 max-height和 height的值都覆蓋掉。