css3 - 請(qǐng)問,如何通過CSS實(shí)現(xiàn)高度height隨寬度width變化而變化,保持長(zhǎng)寬比例不變,寬度是根據(jù)父元素寬度變化的?
問題描述
請(qǐng)問,如何通過CSS實(shí)現(xiàn)高度height隨寬度width變化而變化,保持長(zhǎng)寬比例一致,寬度是根據(jù)父元素寬度變化的,
既:width:20%
問題解答
回答1:騷年,數(shù)月之前吾曾于某高山僻壤處尋得一奇淫技巧可與爾一觀。然而這樣的技巧并沒有什么卵用,切記切記!
html:<p class = 'father'> <p class = 'daughter'></p> // 父女情深</p>css:.father { width: 70%;}.daughter { width: 90%; height: 0; padding-top: 60%; background: black;}
這樣的技巧僅僅讓人對(duì)某個(gè)知識(shí)點(diǎn)有一些深刻的認(rèn)識(shí),這里是想讓人了解到:上下邊距的百分比數(shù)值是以父元素寬度作為參照的。要想實(shí)現(xiàn)你題目中的條件,用js,簡(jiǎn)單得很。不必費(fèi)盡周章絞盡腦汁非要用css實(shí)現(xiàn)。
回答2:加個(gè)jsbinhttp://jsbin.com/kufuwaxiji/1/edit?html,output
寬高保持不變,你參考下,內(nèi)容要絕對(duì)定位
<!DOCTYPE html><html><head> <meta charset='utf-8'> <title>css_square</title> <style> .main {width: 600px; } .rect1 {position: relative;width: 50%;background: #f30;padding-bottom: 50%; } .rect1 > .inner, .rect2 > .inner {padding: 100px;position: absolute;top: 50%;left: 50%;background-color: #0ac;-webkit-transform: translate(-50%, -50%); } .rect2 > .inner {background-color: #0cc; } .rect2 {position: relative;width: 50%;background: #f30; } .rect2:before {content: '';display: block;padding-top: 100%;width: 100%;background: #08c; } </style></head><body><input type='range' min='1' max='300' id='range'><hr>純CSS實(shí)現(xiàn)正方形布局<hr><p class='main'> <p class='rect1'><p class='inner'></p> </p> <hr> <p class='rect2'><p class='inner'></p> </p></p><script>document.querySelector(’#range’).addEventListener(’change’, function(e) { document.querySelector(’.main’).style.width = 600 + this.value/1 + ’px’})</script></body></html>回答3:
JS實(shí)現(xiàn)吧標(biāo)準(zhǔn)CSS實(shí)現(xiàn)不了。
如果確實(shí)需要,神奇的IE6還是可以實(shí)現(xiàn)的。
相關(guān)文章:
