Search code examples
htmlcssmedia-queries

Can I use @media in my HTML page?


I would like to use @media in my html page but I don't know if that is possible or not.

I have seen W3schools do this:

<picture>
  <source srcset="img_smallflower.jpg" media="(max-width: 400px)">
  <source srcset="img_flowers.jpg">
  <img src="img_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

So I thought maybe I can do this:

<form>
    <input id="submit" type="submit" value="zoeken" media="(min-width: 613px)">
    <input id="submit" type="submit" value="*" media="(max-width: 613px)">
    <input type="text" name="search" placeholder="Artikelen..">
</form>

So I tried to let the 1 button show if its under 613px, the other if its above 613px. But it just shows them next to each other. Is this media thing only possible with <picture> and <video>?


Update

Answer taught me it's only possible with some tags.

I could make it work with media-queries with display:none for example:

<form>
    <input id="submit" type="submit" value="zoeken" class="bigger680">
    <input id="submit" type="submit" value="..." class="smaller680">
    <input type="text" name="search" placeholder="Artikelen..">
</form>

<style>
    @media only screen and (max-width: 680px) {
        .bigger680{
            display: none;
        }
    }

    @media only screen and (min-width: 680px) {
        .smaller680{
            display: none;
        }
    }
</style> 

Solution

  • You can use them in a limited way on some elements like a, area or link like documentated here: http://www.w3schools.com/tags/att_media.asp

    But I wouldn't recommend this, cause it violates the separation of concerns. HTML is designed to organize the structure of a page, where CSS is responsible for the presentation of those elements. You should use CSS classes/ids to apply our CSS.

    It also gives you more flexibility, since its possible to apply media queries to every element without limitation. Using the inline approach, you propably will have some queries in the html document and others in our stylesheet.