我可以根据基于百分比的宽度设置div的高度吗? [英] Can I set the height of a div based on a percentage-based width?

查看:126
本文介绍了我可以根据基于百分比的宽度设置div的高度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个div,宽度为body的50%。如何使其高度等于该值?因此,当浏览器窗口宽度为1000px时,div的高度和宽度都是500像素。

解决方案

CSS如果你愿意忍受一些限制和跨浏览器的问题。然而,它可以轻松,灵活地使用Javascript。如果你需要一个纯CSS解决方案,请参阅其他答案。



将div的宽度设置为(例如)50%,使用JavaScript来检查其宽度,然后设置相应的高度。这里是一个代码示例(我使用jQuery,一个JavaScript库):



  $(function dynamicheight'); var width = div.width(); div.css('height',width);});  

  #dynamicheight {width:50%; / *只是为了看起来:* / background-color:cornflowerblue; margin:25px;}  

 < script src =https ://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js>< / script>< div id =dynamicheight>< / div>  



如果您希望框在调整大小时调整浏览器窗口,代码到函数并调用它在窗口的resize事件。这里有一个演示(查看示例全屏和调整浏览器窗口):



  $(window).ready updateHeight); $(window).resize(updateHeight); function updateHeight(){var div = $('#dynamicheight'); var width = div.width(); div.css('height',width);}  

  #dynamicheight {width:50%; / *只是为了看起来:* / background-color:cornflowerblue; margin:25px;}  

 < script src =https ://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js>< / script>< div id =dynamicheight>< / div>  


Let's say I've got a div that has a width of 50% of the body. How do I make its height equal to that value? So that when the browser window is 1000px wide, the div's height and width are both 500px.

解决方案

This can be done with pure CSS if you're willing to put up with some restrictions and cross-browser issues. However, it can be done easily and flexibly with Javascript. If you need a pure CSS solution, see the other answers.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example (I'm using jQuery, a JavaScript library):

$(function() {
    var div = $('#dynamicheight');
    var width = div.width();
    
    div.css('height', width);
});

#dynamicheight
{
    width: 50%;
    
    /* Just for looks: */
    background-color: cornflowerblue;
    margin: 25px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="dynamicheight"></div>

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

$(window).ready(updateHeight);
$(window).resize(updateHeight);

function updateHeight()
{
    var div = $('#dynamicheight');
    var width = div.width();
    
    div.css('height', width);
}

#dynamicheight
{
    width: 50%;
    
    /* Just for looks: */
    background-color: cornflowerblue;
    margin: 25px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="dynamicheight"></div>

这篇关于我可以根据基于百分比的宽度设置div的高度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆