css實(shí)現(xiàn)div寬度自適應(yīng),寬高保持等比縮放 | 您所在的位置:網(wǎng)站首頁 › 屬馬人一生最旺的顏色被子 › css實(shí)現(xiàn)div寬度自適應(yīng),寬高保持等比縮放 |
css實(shí)現(xiàn)div寬度自適應(yīng),寬高保持等比縮放
1、方式一2、方式二3、方式三4、方式四
1、方式一
.square {
width: 30%;
height: 30vh;
border: 1px solid red;
background-color: #00FFFF;
}
由于margin, padding的百分比數(shù)值是相對(duì)父元素的寬度計(jì)算的,只需將元素垂直方向的一個(gè)padding值設(shè)定為與width相同的百分比就可以制作出自適應(yīng)正方形了。但要注意,僅僅設(shè)置padding-bottom是不夠的,若向容器添加內(nèi)容,內(nèi)容會(huì)占據(jù)一定高度,為了解決這個(gè)問題,需要設(shè)置height: 0。 .square2 { width: 30%; height: 0; padding-bottom: 30%; border: 1px solid red; background-color: #00FFFF; }利用偽元素的margin(padding)-top撐開容器。max-height屬性失效的原因是: max-height屬 性只限制于 height,也就是只會(huì)對(duì)元素的content height起作用。 解決方法是:用一個(gè)子元素?fù)伍_content部分的高度,從而使max-height屬性生效。 首先需要設(shè)置偽元素,其內(nèi)容為空,margin-top設(shè)置 為100%。 但要注意,若使用垂直方向上的margin撐開父元素,僅僅設(shè)置偽元素是不夠的,這涉及到margin collapse外邊距合并的概念,由于容器與偽元素在垂直方向發(fā)生了外邊距合并,所以撐開父元素高度并沒有出現(xiàn),解決方法是在父元素上觸發(fā)BFC:設(shè)置overflow:hidden。 .square3 { width: 20%; /* 處理外邊距合并 */ overflow: hidden; border: 1px solid red; background-color: #00FFFF; } .square3::after { content: ''; display: block; margin-top: 100%; }若使用垂直方向上的padding撐開父元素,則不需要觸發(fā)BFC。子元素的100%就相當(dāng)于父元素的20% .square4 { width: 20%; border: 1px solid red; background-color: #00FFFF; } .square4::after { content: ''; display: block; padding-top: 100%; }
|
今日新聞 |
推薦新聞 |
專題文章 |
CopyRight 2018-2019 實(shí)驗(yàn)室設(shè)備網(wǎng) 版權(quán)所有 |