css3 - 请问,如何通过CSS实现高度height随宽度width变化而变化,保持长宽比例不变,宽度是根据父元素宽度变化的?
黄舟
黄舟 2017-04-17 11:12:30
0
3
829

请问,如何通过CSS实现高度height随宽度width变化而变化,保持长宽比例一致,宽度是根据父元素宽度变化的,

既:width:20%

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
Ty80

In this year, a few months ago, I found a strange obscene technique in a remote place in a high mountain that you can have a look at. However, such techniques are of no use, so remember!

html:


<p class = "father">
    <p class = "daughter"></p>    // 父女情深
</p>



css:
.father {
    width: 70%;
}
.daughter {
    width: 90%; height: 0;
    padding-top: 60%;
    background: black;
}
Such techniques only give people some in-depth understanding of a certain knowledge point. What I want people to understand here is that the percentage values ​​of the top and bottom margins are based on the width of the parent element as a reference. If you want to realize the conditions in your question, use js, which is very simple. There is no need to rack your brains to implement it with css.
小葫芦

Add onehttp://jsbin.com/kufuwaxiji/1/edit?html,output The width and height remain unchanged. For your reference, the content must be absolutely positioned

<!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实现正方形布局
<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>
伊谢尔伦

JSLet’s do it Standard cannot be achieved. If you really need it, the magic can still be achieved.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template