Home  >  Q&A  >  body text

Automatically adapt to div containers in Javascript

I have a div with different sizes. It can have the following dimensions: Height: 780, Width: 1390, or Height: 524, Width: 930.

React applications are displayed on two types of screens: Full HD 1920x1080 and 4K 3840x2054.

I want the div to be different sizes and screens so that it always has the same proportions in the screen and the same dimensions in both types of screens.

For example, I want the div to be different on other types of screens, such as tablets, smartphones, or 1920x1200 screens. I want to make it as flexible as possible.

In 4K the div looks much smaller than the rest of the screen, while in Full HD it takes up most of the screen.

I tried using vh and vw as follows:

function convertPxToVH(px) {
    var vh = (px / 1080) * 100;
    return vh;
  }

  function convertPxToVW(px) {
    var vw = (px / 1920) * 100;
    return vw;
  }

This way I will get the same vh and vw for each type of screen. But it doesn't work well because in 4k screen the div has more space in full HD.

This is the result I want to achieve (obviously I want it to fit other types of screens as well). Thanks in advance to everyone who helps me

P粉806834059P粉806834059423 days ago621

reply all(1)I'll reply

  • P粉366946380

    P粉3669463802023-09-14 16:43:48

    You can achieve this by using css with width and height and vw and vh.

    vw represents a percentage of the viewport width, so 80vw is 80% of the width. This is the same as vh, just at a different height.

    body { background-color: #00305e; }
    
    .keep-prop {
      background-color: #ffc700;
      width: 80vw;
      height: 80vh;
      margin: 0 auto;
    }
    <!DOCTYPE html>
    <html>
    
      <head>
      </head>
      
      <body>
    
        <div class="keep-prop">
        </div>
      </body>
    
    </html>

    reply
    0
  • Cancelreply