Can I scale a div's height proportionally to its width using CSS?

前端 未结 9 1126
面向向阳花
面向向阳花 2020-12-07 16:34

Can I set any variable in CSS like I want my div height to always be half of width my div scales with the screen size width for div is in percent

相关标签:
9条回答
  • 2020-12-07 16:57

    For anyone looking for a scalable solution: I wrote a small helper utility in SASS to generate responsive proportional rectangles for different breakpoints. Take a look at SASS Proportions

    Hope it helps anybody!

    0 讨论(0)
  • 2020-12-07 17:00

    You can use the view width to set the height. 100 vw is 100% of the width. height: 60vw; would make the height 60% of the width.

    0 讨论(0)
  • 2020-12-07 17:00

    One way usefull when you work with images, but can be used as workaround otherwise:

    <html>
    <head>
    </head>
    <style>
        #someContainer {
            width:50%;
            position: relative;
        }
        #par {
            width: 100%;
            background-color:red;
        }
        #image {
            width: 100%;
            visibility: hidden;
        }
        #myContent {
            position:absolute;
        }
    </style>
    <div id="someContainer">
        <div id="par">
            <div id="myContent">
                <p>
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                </p>    
            </div>
            <img src="yourImage" id="image"/>
        </div>
    </div>
    </html>
    

    To use replace yourImage with your image url. You use image with width / height ratio you desire.

    div id="myContent" is here as example of workaround where myContent will overlay over image.

    This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

    0 讨论(0)
提交回复
热议问题