Latest web development tutorials
 

CSS3 Media Queries - Examples


CSS3 Media Queries - More Examples

Let us look at some more examples of using media queries.

We will start with a list of names which function as email links. The HTML is:

Example 1

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
}

ul li a {
    color: green;
    text-decoration: none;
    padding: 3px;
    display: block;
}
</style>
</head>
<body>

<ul>
  <li><a data-email="[email protected]" href="mailto:[email protected]">John Doe</a></li>
  <li><a data-email="[email protected]" href="mailto:[email protected]">Mary Moe</a></li>
  <li><a data-email="[email protected]" href="mailto:[email protected]">Amanda Panda</a></li>
</ul>

</body>
</html>
Try it Yourself »

Notice the data-email attribute. In HTML5, we can use attributes prefixed with data- to store information. We will use the data- attribute later.


Width from 520 to 699px - Apply an email icon to each link

When the browser's width is between 520 and 699px, we will apply an email icon to each email link:

Example 2

@media screen and (max-width: 699px) and (min-width: 520px) {
    ul li a {
        padding-left: 30px;
        background: url(email-icon.png) left center no-repeat;
    }
}
Try it Yourself »

Width from 700 to 1000px - Preface the links with a text

When the browser's width is between from 700 to 1000px, we will preface each email link with the text "Email: ":

Example 3

@media screen and (max-width: 1000px) and (min-width: 700px) {
    ul li a:before {
        content: "Email: ";
        font-style: italic;
        color: #666666;
    }
}
Try it Yourself »

Width above 1001px - Apply email address to links

When the browser's width is above 1001px, we will append the email address to the links.

We will use the value of the data- attribute to add the email address after the person's name:

Example 4

@media screen and (min-width: 1001px) {
    ul li a:after {
        content: " (" attr(data-email) ")";
        font-size: 12px;
        font-style: italic;
        color: #666666;
    }
}
Try it Yourself »

Width above 1151px - Add icon as we used before

For browser widths above 1151px, we will again add the icon as we used before.

Here, we do not have to write an additional media query block, we can just append an additional media query to our already existing one using a comma (this will behave like an OR operator):

Example 5

@media screen and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
    ul li a {
        padding-left: 30px;
        background: url(email-icon.png) left center no-repeat;
    }
}
Try it Yourself »

Examples

More Examples

Use the list of email links on a sidebar in a web page
This example puts the list of email links into the left sidebar of a webpage.