Using media query syntax
Let’s take a look at the following example. If you resize your web browser
window to make its width smaller than 600px
, the background will be red
.
Otherwise, the background will be yellow
.
CSS code:
HTML code:
Result:
As you noticed, there are 2 media query blocks which wrap some CSS rules inside. I call them conditional styles; Because the CSS code inside a media query block is inactive unless a certain condition is satisfied.
In the example, the condition of the first media query is: viewport’s width is
not larger than 599px
. The second media query’s condition is: viewport’s width
is greater than or equals to 600px
.
More about media query conditions
Besides creating constrains based on viewport’s dimensions, we also have other choices:
- Media type:
screen
,print
,speech
,all
- Viewport’s orientation:
portrait
orlandscape
Let’s say if you’re publishing your book’s content on your website as blog posts (not in pdf form). You may want to help your audiences to print only main contents of the webpages if they want. So, you can create specific styles target printers to hide all ads and navigation bars. We also assume that the contents will be printed in portrait mode:
CSS code:
Creating a responsive navigation bar
To keep this post simple and purely focus on introducing media query syntax, I have to move this section to a single article. So, please keep this tab open and click on the link below to go to the article:
Tutorial: Creating a responsive navigation bar
Have you finished the tutorial and successfully created a responsive navigation
bar? :D
Found some joyful moment? :D
I know that was a tough job. Just a simple responsive navigation bar and it takes us ~100 lines of CSS code. What if I tell you that we don’t have to write that much CSS code to achieve the same result (or even better)? :D.
See you in the next tutorial.