-4

I want to know how to set a height to a <div> so that if height resized, the width will re-size equally e.g. if the width of a <div> is being reduced via the user re-sizing a browser window, the height will be reduced in the same proportion.

How is this possible?

scniro
  • 16,844
  • 8
  • 62
  • 106
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167

3 Answers3

1

Here is solution with an image.

HTML

<div>
  <img src="transparent-image.png" alt=""/>
</div>

CSS

  div { display: inline-block; }
  img { max-width: 100%; }

Demo

Ilya B.
  • 952
  • 7
  • 13
0

There are a few ways to do this. This example is JavaScript free but will require a parent element. Observe the following...

<div id="container">
    <div id="element"></div>
</div>

#container {
    display: inline-block;
    position: relative;
    width: 100px;
}
#container:after {
    content: '';
    display: block;
    margin-top: 100%;
}
#element {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: dodgerblue;
}

Whenever width is changed, so is height, equally. Supplied below is a demo, while using jQuery, is just for an easy way to manipulate the element width.

// -- 100 x 100
$('#container').click(function() {
    $(this).width(50); // -- 50 x 50
});

JSFiddle Link - demo

JSFiddle Link - additional demo - % based - (re-size output window to see scaling)

Additionally, for a short and much simpler answer, use vw units. Observe the following...

<div></div>

div {
    width:20vw;
    height:20vw;
    background-color: dodgerblue;
}

JSFiddle Link - vw demo

Here is a decent writeup on vw and other similar units that may be of interest

scniro
  • 16,844
  • 8
  • 62
  • 106
0

I doubt if it is possible with only css and html, since window resizeing is dynamic.I have created this snippet for demo and you can change according to your convience.Hope this code will be useful.

HTML

<div class="defaultDimen" id='defaultDiv'>
    Hello Default Div
</div>

CSS

.defaultDimen{
    height:30%;
    width:20%;
    border:1px solid red;
    border-radius:6px;

}

JS & jQuery

function _resizeDiv(options){
var ratio=options.ratio;
    var elem = $(options.element);
    var _getWidth = elem.width();
    var _getHeight = elem.height();

    elem.css({'width':'30%',
              'height':elem.width()*ratio})

}

$(window).resize(function(){
    var elem = document.getElementById('defaultDiv');
    _resizeDiv({
     ratio:0.5,
        element:elem
    })
})

You can specify the ratio of height & width you want. jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78