Home > Blockchain >  Stack Two Divs When Screen Is Narrowed
Stack Two Divs When Screen Is Narrowed

Time:11-24

I have two divs with an empty partition in the middle:

<div>
    <div style='float:left; width:10%'>A<div>
    <div style='float:right; width: 80%'>B</div>
<div>

enter image description here When I narrow the screen, I want the A on top of B.

enter image description here

One solution that I've seen is to float A and B left, but the problem is that I need to keep that empty buffer between A and B when they are side by side. Floating A and B to the left causes them to be right next to each other while horizontal.

I've also thought about creating an empty fixed width div between A and B and floating all to the left, However, I do NOT want an empty buffer to stack in between A and B vertically.

Is there a different solution I could use here?

CodePudding user response:

CSS Grid is a good solution for this one. See snippet below. You will have to "Full Page" the snippet to see the desktop vs. mobile version. The breakpoint is set to 720px.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">

  <link rel="icon" href="images/logo.png" type="image/x-icon">

  <title>Test</title>

  <style>
    body {
      font-family: monospace;
      font-size: 32px;
      padding: 50px;
      color: white;
    }

    .container {
      display: flex;
      width: 100%;
      flex-direction: column;
    }

    @media only screen and (min-width: 720px) {
      .container {
        grid-column: 1 / -1;
        grid-gap: 24px;
        display: grid;
        grid-template-columns: 10% 80%;
        justify-content: center;

      }
    }



    .box-1 {
      background: #7FB9D5;
      width: 100%;
      height: 200px;
      justify-content: center;
      align-items: center;
      display: flex;
      margin: 12px 0;
    }

    .box-2 {
      background: #FF5C5C;
      width: 100%;
      height: 200px;
      justify-content: center;
      align-items: center;
      display: flex;
      margin: 12px 0;
    }
  </style>
</head>

<body>

  <div class="container">
    <div class="box-1">A</div>
    <div class="box-2">B</div>
  </div>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

One solution is to use a flexbox layout with flex-wrap set to wrap and with a gap of whatever you need.

Here's a guide with examples: https://web.archive.org/web/20211121030934/https://css-tricks.com/snippets/css/a-guide-to-flexbox/

  • Related