2016-04-14 55 views
0

標題部分中的我的標識應始終與父高度相同。圖像高度應該是父元素的高度

HTML

<header> 
    <div id="logo"> 
     <a href="/"> 
     <img src="img/logo.png" alt="Logo" /> 
     </a> 
    </div> 
</header> 

CSS

*, *:before, *:after { 
    box-sizing: border-box; 
} 

header { 
    background-color: rgb(255,255,255); 
    height: 50px; 
    padding: 10px; 
} 

header #logo img { 
    height: auto; 
    max-height: 100%; 
    max-width: 100%; 
} 
+0

洙,你有什麼問題嗎?或js-fiddle? – AchmadJP

回答

2

你可以改變<img><div>然後使用background-imagebackground-size: contain。請注意,這是一張256 x 256像素的圖像,但是background-size: contain會將圖像壓縮到<div>的尺寸內,而不會裁剪或變形。此外,由於徽標現在是<div>(塊級元素),而不是<img>(內聯級元素),因此height:100%將以您期望的方式工作。下面

引用片段

#logo { 
    height: 100%; 
    width: 100%; 
} 
.img { 
    background: url(https://www.w3.org/html/logo/downloads/HTML5_Badge_256.png) no-repeat; 
    background-size: contain; 
    height: 100%; 
} 

*, 
 
*:before, 
 
*:after { 
 
    box-sizing: border-box; 
 
} 
 
header { 
 
    background-color: rgb(255, 255, 255); 
 
    height: 50px; 
 
    padding: 10px; 
 
} 
 
#logo { 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
.img { 
 
    background-image: url(https://www.w3.org/html/logo/downloads/HTML5_Badge_256.png); 
 
    background-repeat: no-repeat; 
 
    background-size: contain; 
 
    height: 100%; 
 
}
<header> 
 
    <div id="logo"> 
 
    <a href="/"> 
 
     <div class="img"></div> 
 
    </a> 
 
    </div> 
 
</header>

參考文獻:

2

@ zer00ne的答案肯定是我會去用它的方式,爲您提供了更多的控制。

在附註上;你已經將你的標題設置爲固定的50px高度。您只需在尺寸和位置上進行硬編碼即可快速修復。

<head> 

<style type="text/css"> 

header { 
    background-color: rgb(255,255,255); 
    height: 50px; 
    padding: 10px; 
} 

header #logo img { 
    height: 70px; 
    margin-top: -10px; /*these can be removed and the height set to 50, but it will contain it within the padding*/ 
    margin-left: -10px; 
} 

</style> 
</head> 

<header> 
    <div id="logo"> 
     <a href="http://placekitten.com/500/200"> 
     <img src="http://placekitten.com/500/200" alt="Logo" /> 
     </a> 
    </div> 
</header> 

原始圖像是500x200(http://www.placekitten.com < 3)