Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use CSS Media Queries to Dynamically Apply Styles


    Today the majority of internet traffic comes from mobile devices. So it is essential to understand how to make styles dynamic to different viewport sizes. In this lesson we assign some CSS to a ul and modify the styles depending on the viewport size.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: Our navigation could definitely use some styles right now, so let's go UL display flex and then justify content space between. When we save that and refresh, we'll see that our navigation is now spread out across the page. Displaying our UL block as flex creates a flex container.

    Flex is a powerful and simple way of dynamically positioning our elements. When used with justify content space between, it successfully spreads our nav items out evenly. This works great with our website pulled up on a laptop, but if we were to shrink the page to emulate a mobile view, our navigation becomes unreadable.

    Back inside of our CSS, let's do an at media max width 700 pixels. Then we'll create a UL block saying display block. With a refresh, we'll see that our navigation goes back to the original state it was in. This makes it much easier for users to use our website on smaller devices.

    As we can see, using media queries are useful when we want to modify our site or app, depending on devices general type such as the viewport width.

    Whenever all of the media feature expressions which are defined inside the parentheses here compute to true, the CSS defined within the blocks will apply to the website. What our max width is saying here, if our viewport is 700 pixels or less, apply the following styles. If we open up our viewport larger than 700, we'll see that it goes back to display flex.

    We can accomplish this same functionality by switching to min width and switching the displays. Now we're saying if the min width of the viewport is 700 pixels or greater, apply flex. If smaller, apply block.

    Logical operators such as and can be used to compose a complex media query. Here we're saying only display flex between the pixels of 700 and 1,000. Once we get past 1,000, it goes back to display block.

    A couple of other media features you can test on is min height and max height. Finally, you can also check for orientation, whether the website is in portrait or landscape mode.