如果不給一個元素具體的height
,它就會自動適應(yīng)其內(nèi)容的高度。假如我們希望width
也有類似的行為,該怎么辦呢?
<p>some text [···]</p>
<figure>

<figcaption>
background-color background-position background-size
</figcaption>
</figure>
<p>some text [···]</p>
給figure
加了一道邊框,在默認(rèn)情況下,看起來就是下圖這樣的:
但是我們想要的效果是這個
figure
元素能跟它所包含的圖片一樣寬,而且是水平居中的。那就要用到
width
和height
的** min-content
屬性了。這個關(guān)鍵字將解析為這個容器內(nèi)部最大的不可斷行元素的寬度**(即最寬的單詞、圖片或具有固定寬度的盒元素)
figure {
border:1px solid #ace;
width: -webkit-min-content; /*考慮到兼容性,加前綴*/
width: -moz-min-content;
width: min-content;
margin:auto;
}
為了給舊版本瀏覽器提供一個平穩(wěn)的回退樣式,我們需要在使用這個技巧的同時,提供一個固定的
maax-width
值:
figure {
max-width:300px;
max-width:min-content;
margin:auto;
}
figure > img{
max-width:inherit;}
對于現(xiàn)代瀏覽器來說,后一條 max-width
聲明會覆蓋前一條。如果figure 的尺寸是由內(nèi)部因素決定時,第二條規(guī)則中的 max-width:inherit;
就不會生效了。
參考書籍:Lea Verou《CSS揭秘》