Search code examples
htmlcsscss-floatwidth

Width of div is not applied by media query


I'm trying to make full width horizontal menus using the methods display:inline-block as well as float:left. It all works, except that the media query is not applying the width:100% declaration. The test color is applied though which indicates that the media query is working.

Relevant section from HTML document

<nav class="display">
  <!-- Weird comments to prevent space between elements -->
  <div class="navitem">Section 1</div><!--
  --><div class="navitem">Section 2</div><!--
  --><div class="navitem">Section 3</div><!--
  --><div class="navitem">Section 4</div>
</nav>

<nav class="float">
  <div class="navitem">Section 1</div>
  <div class="navitem">Section 2</div>
  <div class="navitem">Section 3</div>
  <div class="navitem">Section 4</div>
</nav>

Relevant section from stylesheet

.display .navitem {
  display: inline-block;
  width: 25%;
}

.float .navitem {
  float: left;
  width: 25%;
}

.float::after {
  clear: left;
  content: "";
  display: table;
}

@media screen and (max-width:800px) {
  .navitem {
    width: 100%;
    color: blue;
  }
}

I've been trying around for an hour and just can't figure out why the width won't change. What am I missing?

Full code: jsfiddle.net


Solution

  • You could use display:flex

    html

      <nav>
        <div>Section 1</div>
        <div>Section 2</div>
        <div>Section 3</div>
        <div>Section 4</div>
      </nav>
    

    css

    nav > div {
      flex: none;
      color: black;
    }
    
    @media screen and (min-width:800px) {
    
      nav {
        display: flex;
      }
    
      nav > div {
        flex: 1;
        color: blue;
      }
    }
    

    https://jsfiddle.net/z7w2ms34/