Search code examples
htmlcssmedia-queries

Why doesn't my @media query work with the picture tag?


I switched all my img tags to picture tags so I could add webp images along with png images to fall back on. I also have a media query that's supposed to shrink the images to 65x65 when on a phone but instead it leaves the images as 100x100. How do I fix this?

@media only screen and (max-width: 600px) {
  .charactertable picture {
    width: 65px;
    height: 65px;
  }
}
<table id="myTable2" class="charactertable">
  <tr>
    <th class="tablename" onclick="sortTable(0)">Name</th>
    <th class="tableimageheader">Image</th>
    <th class="tablepersonality" onclick="sortTable(2)">Personality</th>
    <th class="tablespecies" onclick="sortTable(3)">Species</th>
    <th class="tablebirthday" onclick="sortTable(4)">Birthday</th>
    <th class="tablecatchphrase">Catchphrase</th>
  </tr>

  <tr>
    <td class="begintable">Admiral</td>
    <td>
      <picture>
        <source type="image/webp" srcset="Character_images/Admiral.webp">
        <img alt="Admiral" src="images/Admiral.jpg">
      </picture>
    </td>
    <td>Cranky</td>
    <td>Bird</td>
    <td><span class="date">0127</span>January 27th</td>
    <td class="endtable">"aye aye"</td>
  </tr>


Solution

  • Style it on the <img> tag. Think of <picture> as more of a meta element that provides additional rendering "instructions". The element that is actually rendered, and ultimately takes the styles, is the <img> itself. Note that the fact that you are using a media query is irrelevant, you'll always want to attach your styles on the <img> tag.

    Read more about <picture> on MDN here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture

    @media only screen and (max-width: 600px) {
      .charactertable img {
        width: 65px;
        height: 65px;
      }
    }
    <table id="myTable2" class="charactertable">
      <tr>
        <th class="tablename" onclick="sortTable(0)">Name</th>
        <th class="tableimageheader">Image</th>
        <th class="tablepersonality" onclick="sortTable(2)">Personality</th>
        <th class="tablespecies" onclick="sortTable(3)">Species</th>
        <th class="tablebirthday" onclick="sortTable(4)">Birthday</th>
        <th class="tablecatchphrase">Catchphrase</th>
      </tr>
    
      <tr>
        <td class="begintable">Admiral</td>
        <td>
          <picture>
            <source type="image/webp" srcset="https://via.placeholder.com/120x120.webp">
            <img alt="Admiral" src="https://via.placeholder.com/120x120">
          </picture>
        </td>
        <td>Cranky</td>
        <td>Bird</td>
        <td><span class="date">0127</span>January 27th</td>
        <td class="endtable">"aye aye"</td>
      </tr>
    </table>