Can I program the height of the div as a specific percentage of its current width?

Is it possible to provide a div with a width that represents a percentage of the window and a height that is a certain percentage of the current width? Thus, the size of the div changes, but when you resize the browser window, the same aspect ratio is maintained.

Thanks Ciao

+5
source share
5 answers

There the padding trick already answered, but I use a different approach, including two nested divs.

Parent, I set the width. For the child, I use the height value as the unit of the vw container - (means the width of the viewport).

Works well, see here (resizing viewport)

 <div> <div></div> </div> 

CSS

 div { width: 100%; } div > div { background: silver; height: 10vw; } 
+6
source

I use this

Demo 1

 .aspect-ratio { max-width: 100%; } .aspect-ratio:before { content: ''; display: block; width: 100%; padding-bottom: ({height-aspect} / {width-aspect} * 100)%; // for 3 x 4, for instance: 75% } 

Demo 2

If you prefer less than me, you can do mixin:

 .aspectRatio(@widthAspect, @heightAspect) { @aspect: @heightAspect/@widthAspect * 100; max-width: 100%; &:before { content: ''; display: block; width: 100%; padding-bottom: ~"@{aspect}%"; } } 
+5
source

If you set the top and bottom fill of the element as a percentage, it will relate to the width of the element.

+3
source

When you use a percentage in height , it is calculated relative to the height of the generated block containing the block.

Since you want to calculate it in relation to the width, you can use, for example, padding-top .

To avoid affecting the contents, place them in a completely placed package.

 #wrapper { padding-top: 25%; /* ratio */ border: 1px solid; position: relative; } #content { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } 
 <div id="wrapper"> <div id="content"> <p>Foo</p> <p>Bar</p> <p>Baz</p> </div> </div> 
+2
source

Yes with jquery you can get the width and height of the screen, then you can target this div and set the height and width

http://api.jquery.com/width/

jquery div width adjustment

0
source

Source: https://habr.com/ru/post/1208908/


All Articles