skip to Main Content

I am displaying a number of boxes on the screen. These refer to containers of 2 sizes.

On a mobile screen, I want the boxes to reduce in size when the screen horizontal width is too small – keeping the same aspect ratio. How do I accomplish this? I don’t know much about flexboxes to do this.

html {
  font-family: verdana
}
.Container {
  white-space:nowrap;
  display:inline-block;
}
.Bx {
  cursor: pointer;
  display: inline-block;
  height: 2.0em;
  width: 5em;
  border: 1px solid gray;
  margin: 0px;
  box-sizing: border-box;
  background-color: #f7e0f7;
}

.B4 {
  width: 10em;
  background-color: #e0f7ff;
}
<!DOCTYPE html>
<html>

<head>
  <title>Box Test</title>
</head>

<body>
  <b>Box Test</b><br><br> Boxes should shrink <u>maintaining their aspect ratio</u>.<br><br> These boxes should shrink when the longest row cannot fit in the screen horizontally<br>
  <div class="Container">
    R1 <div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><br>
    R2 <div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><div class="Bx"></div><br>
    R3 <div class="Bx B4"></div><div class="Bx"></div><div class="Bx"></div><div class="Bx B4"></div><div class="Bx"></div><br>
    R4 <div class="Bx"></div><div class="Bx"></div></div><br>
    R5 <div class="Bx"></div><div class="Bx B4"></div><div class="Bx"></div><div class="Bx"></div><br>
    R6 <div class="Bx B4"></div><div class="Bx"></div><div class="Bx"></div><br>
  </div>
</body>

</html>

2

Answers


  1. Your best bet is to learn responsive design in the form of grid, flexbox, or media queries. It may be a bit of an upfront investment in learning, but it will certainly pay off over time and cause fewer headaches in the future. I would recommend checking out some tutorials on YouTube; Kevin Powell is a favorite to watch and explains things in a way that’s easy to understand, accompanied by helpful visual aids. I hope this helps. Good luck in your coding journey.

    Login or Signup to reply.
  2. Use CSS @media queries with aspect-ratio

    For example (taken from the mdn webpage below):

    @media (aspect-ratio: 1/1) {
      div {
        background: #f9a; /* red */
      }
    

    For further info, please refer to the mdn webpage
    aspect-ratio info

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search