Search code examples
htmlcssflexboxmedia-queries

Change flexbox-direction on different resolution


Why, on resolutions below 800px, doesn't the flex-direction change? The items are still on one row. The same thing happens if I want to change the order on different resolution.

Here is the HTML and CSS:

body {
  font-weight: bold;
  text-align: center;
  font-size: 16px;
  box-sizing: border-box;
}

main {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

article,
.aside {
  border: 1px solid black;
}

article {
  width: 50%;
}

.aside {
  width: 24%;
}

@media screen and (max-width: 800px) {
  main {
    flex-direction: column;
  }
  main>* {
    width: 100%;
  }
}
<body>
  <main>
    <article class="main-article">
      <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
    </article>
    <aside class="aside aside-1">Aside 1</aside>
    <aside class="aside aside-2">Aside 2</aside>
  </main>
</body>


Solution

  • The flex direction is actually changing correctly, the problem is that you have .aside class outside of the media query and inside the media query, you are using the * for wild card. The class will always take precedence over the wild card. So, you are essentially making the .aside items 24% even at less than 800px.

    body {
      font-weight: bold;
      text-align: center;
      font-size: 16px;
      box-sizing: border-box;
    }
    
    main {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    article,
    .aside {
      border: 1px solid black;
    }
    
    article {
      width: 50%;
    }
    
    .aside {
      width: 24%;
    }
    
    @media screen and (max-width: 800px) {
      main {
        flex-direction: column;
      }
      main > *,
      main > .aside {
        width: 100%;
        border-color: yellow;
      }
    }
    <body>
      <main>
        <article class="main-article">
          <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
        </article>
        <aside class="aside aside-1">Aside 1</aside>
        <aside class="aside aside-2">Aside 2</aside>
      </main>
    </body>

    As you can see, the asides are now full width and it's in column direction.