Andre Roque Andre Roque - 4 months ago 19
HTML Question

Create responsive div element

I don't know if the title is quite correct, but what I want basically is to create a div element that stays proportional to the resolution of the screen. For example, if the width is 1900px I want that the div have:

width: 1115px;
height: 775px;


But if the width of the page is 1050px I want:

width: 620px;
height: 430px;


What should be my CSS to allow this?

So I want that the width is a percentage of the screen, let's say, and the height is based on the width.

Answer

There are two solutions to make the element proportional to the screen, one which depends on your setup.

You can use percentage

width: 20%;

But this only defines a percentage of the parent element, and does not make both your width and height proportional

You can also use viewport units. This defines a percentage of the viewport. If you use viewport width vw you can get a height which is dependent on the width.

height: 10vw; /*10% of viewport width*/
width: 10vw;

You can also setup media queries to handle smaller or bigger screens.

@media (max-width: 300px) {/*10% of 300px is very small, so we change it to 90%*/
 .selector {
   width: 90vw;
 }
}
Comments