resize both width and height of a div while window resize using css

会有一股神秘感。 提交于 2020-01-05 22:29:11

问题


is there any way to resize both width and height of a div in correlation with the browser resize using css? I have already achieved width resize but can't find how to resize the height in correlation.


回答1:


Use viewport-percentage lengths:

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

If you wanted to create a square that maintains an aspect ratio, you could use:

Example Here

.maintain-aspect-ratio {
    width: 25%;
    height: 25vw;
}

These lengths are supported in most modern browsers - support can be found here.


If you want an alternative with more browser support, you could always use the padding-top trick to maintain the aspect ratio.

Alternative Example

.maintain-aspect-ratio {
    position: relative;
    width: 25%;
    background: red;
}
.maintain-aspect-ratio:before {
    content: '';
    display: block;
    padding-top: 100%; /* 1:1 ratio */
}


来源:https://stackoverflow.com/questions/25881469/resize-both-width-and-height-of-a-div-while-window-resize-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!