Set child width relative to its parents height in pure css

前端 未结 3 857
清歌不尽
清歌不尽 2020-12-17 01:48

Since I am new to webprogramming, i have not yet gained much experience in css. Currently I am building a web application with a resizable header. Therefore I wanted to know

3条回答
  •  长情又很酷
    2020-12-17 02:46

    Just assign your parent's height property value to a css variable and then use calc() to assign your child element's width to a value that is 10% of your parent's height.

    Check and run the Code Snippet below for a practical example of what I have described above:

    .parent {
       position: relative;
       --parentHeight: 300px;
       height: var(--parentHeight);
       width: 600px;
       background-color: red;
     }
     .parent .resized {
       height: 100px;
     }
    
     .child {
       position: absolute;
       height: 20%;
       width: calc(var(--parentHeight) / 10);
       background-color: green;
     }

    N.B. In case you need backward-compatibility for IE11, you can use a polyfill as shown in the top answer on this other SO thread.

提交回复
热议问题