Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting div height based on its width

Tags:

html

css

Is it possible to dynamically set a divs width, then set its height to a certain percentage of that width. Something like this:

#myDiv{
    width:%100;
    height: {35% of width};
}

I want to retain the ratio of the width to height of a div regardless of what the width may be.

like image 753
user906357 Avatar asked Jan 09 '15 02:01

user906357


2 Answers

You can do this with CSS by setting the height to zero and then adding a percentage to padding-bottom. You might have to tweak it a little to get the desired outcome but here's a fiddle with an example http://jsfiddle.net/wbq8o3s7/

#myDiv {
  width: 100%;
  height: 0;
  padding-bottom: 35%;
  background-color: #333;
}
<div id="myDiv"></div>
like image 161
Jake Taylor Avatar answered Oct 14 '22 08:10

Jake Taylor


HTML:

<div class='box'> 
    <div class='content'>All your content are belong to us</div> 
</div>

We use two block elements to achieve the desired behaviour, box for width, content for height.

CSS:

.box{
    position: relative;
    width: 50%;     /* desired width */
}
.box:before{
    content: "";
    display: block;
    padding-top: 100%;  /*What you want the height to be in relation to the width*/
}

The Content:
Then set the content to cover the entire box absolutely so no matter the size, it fits!

.content{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

Tada you are done...

SOURCE: Pure CSS

like image 43
Keeghan McGarry Avatar answered Oct 14 '22 06:10

Keeghan McGarry