简体   繁体   English

动态设置 <div> 高度和边距基于相同 <div> 宽度

[英]Dynamically set <div> height & margins based on the same <div> width

I am creating a responsive site and I want to adjust a height based on it's width. 我正在创建一个响应式网站,我想根据其宽度调整高度。 This is going to be a parallax & responsive site. 这将是一个视差和响应站点。 For the site's responsiveness, I decided to have a container element be adaptive and adjust size based on media queries. 为了提高网站的响应速度,我决定让容器元素具有自适应性,并根据媒体查询调整大小。 Then, this child will have a width of 90% or so. 然后,这个孩子将有90%左右的宽度。

I wanted to write either JS or with the help of JQuery to set the height & margins of this based on the new width at each break point. 我想编写JS或借助JQuery来根据每个断点处的新宽度来设置高度和边距。 I think this would be easier then trying to set a new "px" height for each of these break points. 我认为,然后尝试为每个这些断点设置一个新的“ px”高度,会更容易。 And since I want to have some parallax effects, I need to set the s margins as % instead of pixels to get the same effect on multiple devices. 并且由于我想具有一些视差效果,因此我需要将s边距设置为%而不是像素,以在多个设备上获得相同的效果。

Please let me know if any of this doesn't make sense. 请让我知道这是否没有道理。

Thank you very much. 非常感谢你。

If you want the width and height to be the same, you could use: width: 100vw;height: 100vw; 如果希望宽度和高度相同,则可以使用: width: 100vw;height: 100vw;

Here is another solution, for a resizable div that maintains a 16x9 aspect ratio. 对于保持16x9宽高比的可调整大小的div,这是另一种解决方案。 9/16*100=56.25%

http://jsfiddle.net/ks2jH/512/ http://jsfiddle.net/ks2jH/512/

CSS: CSS:

.aspectwrapper {
display: block; 
width: 90%; /* whatever width you like */
background-image: url('http://placehold.it/160x90');
background-size: cover;
background-repeat: no-repeat;    
}
.aspectwrapper::after {
padding-top: 56.25%; /* percentage of containing block _width_ */
display: block;
content: '';
}

HTML: HTML:

<div class="aspectwrapper">

</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM