Media Query with HTML

Support you want to show different images for desktop, tablet and mobile device you can use the following syntax.

Flowers

Media Query with JS

You can define the media query conditions with JS code as you do in a CSS file. You have the window.matchMedia() in Js.

Once you pass the argument like window.matchMedia("(max-width: 700px)") it will return a object MediaQueryList with results of the query.

You can use the following code to make the responsive HTML with JS code.

In this example we will see how to add a breakpoint . You can load two style sheets, one for desktop and the other one is for the mobile device.

This code is only for you to understand the theory behind media query with JS. If you need to build this functionality you can use the Twitter Bootstrap Responsive Code

    <script>
        const mediaQuery = window.matchMedia("(max-width: 700px)")

        function handleTabletChange(e) {
            var element = document.createElement("link");
            element.setAttribute("rel", "stylesheet");
            element.setAttribute("type", "text/css");
            if (mediaQuery.matches) {
                element.setAttribute("href", "mobilestyle.css");
            } else {
                element.setAttribute("href", "desktopstyle.css");
            }
            document.getElementsByTagName("head")[0].appendChild(element);
        }

        // Register event listener
        mediaQuery.addListener(handleTabletChange)

        // Initial check
        handleTabletChange(mediaQuery)

    </script>

Media query Syntax

Now we will see the syntax of the media query

Media Qyery Syntax

At Rule

If you are going to use media query to convert PSD to responsive HTML code you should write the separate CSS code for different devices.

So your starting point is the @media

Media Type

Here you can specify the device you are going to target. If you use the media type “screen” you can target the devices with screen. When we do normal responsive code we use this option because we target desktop, tablet and mobile devices.

This is the full list of media types.

  • all: all devices
  • screen: for screen such as desktop,tablet and mobile
  • print: to view your document in print preview,you can use this option
  • speech: for speech synthesizers

Media Feature

You can use the media type to select the device then you have to specify the size of the screen which you are going to target. So you can use the media feature min-width(320px) and max-width(768px)

This will target the device with minimum width = 320px and maximum width = 768px

Operator

You can use the logical operators and, or and only. These operators can be used to make complex media queries.