Neat way to set height of empty div to the width of its fluid-width container :)

Neat way to set height of empty div to the width of its fluid-width container :)

ek1

Member
Local time
14:36
Joined
Oct 6, 2019
Messages
81
Pronouns
She/her

height: 100%; wasn't working for me so I fiddled around for a bit and came across a solution that I've never seen before!

Code:
.square {
   width: 100%;
   height: auto;
   padding: 50% 50%;
   box-sizing: border-box;
}

And if you set width to 60% and padding to 30% 30% for example that works too!

Just thought I'd share as I haven't seen hit around before and it worked perfectly for me!

 
Last edited:

Gummibeer

Astroneer
Moderator
Local time
18:36
Joined
Oct 5, 2019
Messages
1,169
Pronouns
he/him

JavaScript:
.embed-responsive-21by9:before {
    padding-top: 42.8571428571%;
}

That's more common because it doesn't conflict with real element styles.

 
Last edited:

Gummibeer

Astroneer
Moderator
Local time
18:36
Joined
Oct 5, 2019
Messages
1,169
Pronouns
he/him

Where on earth does that number come from! 😆
Simple percentage calculation. 😉
100/21*9

I use it quite common to have images in a large size but not covering the whole 16*9 screen.

The trick works the same for 16*9, 4*3, 1*1 or whatever aspect ratio you want to use.

 
Last edited:

VoidlessSeven7

New member
Local time
19:36
Joined
Nov 20, 2019
Messages
4

height: 100%; wasn't working for me so I fiddled around for a bit and came across a solution that I've never seen before!

Code:
.square {
   width: 100%;
   height: auto;
   padding: 50% 50%;
   box-sizing: border-box;
}

And if you set width to 60% and padding to 30% 30% for example that works too!

Just thought I'd share as I haven't seen hit around before and it worked perfectly for me!

Do you mind showing a codepen with the solution applied? Cause I don't fully get what you're trying to accomplish

 

Adam

Mr. Webwide
Administrator
Local time
17:36
Joined
Sep 24, 2019
Messages
1,257
Pronouns
he/him

height: 100%; wasn't working for me so I fiddled around for a bit and came across a solution that I've never seen before!

Code:
.square {
   width: 100%;
   height: auto;
   padding: 50% 50%;
   box-sizing: border-box;
}

And if you set width to 60% and padding to 30% 30% for example that works too!

Just thought I'd share as I haven't seen hit around before and it worked perfectly for me!

Used this today, thank you for sharing! Was great for responsive thumbnail images.

 
Top