. Note that the media queries in this example would have been true if the keyword ' not ' had been added to the beginning of the media query. To avoid circular dependencies, it is never necessary to apply the style.">

Essay On Media Css Query


Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

When we talk about Cascading Style Sheets (CSS), we associate it with styling an HTML page in a browser. But CSS is capable of handling more that just that. Since CSS2 was introduced, we could specify stylesheets for specific media types such as screen or print. Now with 'media queries' in CSS3, we are able to target specific screen sizes.

We can have different blocks of CSS code for different screen and device sizes. If this idea doesn't make you jump from your seat, then you're probably missing the point. In today's world, users view web pages on a wide range of screens. Screens can range from the large displays on their work stations, to their laptops on the air plane, to their iPad or other tablets while sitting in the park and finally on their small mobile phone screens on the go.

Imagine, as a web developer, if you had to build and maintain multiple version of each page to cater to each screen. I, for one, would certainly have switch careers and probably worked at a bakery. Anyway, thankfully for me and all my happy clients, I didn't join a bakery. CSS3 introduced media queries and made life for web developers exciting once again.

If you've styled print documents with CSS, then you are already familiar with defining different styles for different devices. With media queries, we'll take this to a new level. Rather than looking at what device it is, we will look at what capabilities the device has. More specifically, we will look at the following:
  • height and width of the device
  • height and width of the browser
  • screen resolution
  • orientation of the device (for mobile phones and tablets; portrait or landscape)

If your browser supports media queries, then you're good to go. Before we jump into seeing how it works, click here to see if a working example. If you have a mobile phone that allows you to browser, open the link on it and see the difference. As an alternative, reduce the width of the window to 480 pixels and you will immediately see the difference.

Here are screenshots of the page at different widths.

Page layout of desktop screen.

Page layout of mobile phone.

Different Styles for Different Screens: How it Works

You must be thinking that to achieve this, you will have to learn a whole new chapter of CSS. Fortunately you don't have to. All it takes is a few extra lines of code, or sometimes just a few words. The simplest way to use media queries is to have a block of CSS code in the same stylesheet file. So all the CSS that is specific to mobile phones, would be defined in the following block:

@media only screen and (max-device-width: 480px) {
/* define mobile specific styles come here */

Usually we would define this at the end of the file in order to leverage the cascading property of CSS. The background color, the borders and other common attributes would typically be defined above and wont be changed here. The following properties are the ones that we would replace most often:

  • width
  • height
  • float
  • margins

For example, let's say the logo of the company is 600 pixel wide on the desktop version of the website. Now on a device with a width of 480 pixels, the scroller will appear and that is not desirable. So we should have a smaller version of the logo and the CSS file would look like this:

#logo { background: url(images/logo.png); width: 600px; border: 1px #ccc solid; }
@media only screen and (max-device-width: 480px) {
#logo { background: url(images/logo_mobile.png); width: 440px; }

If you notice, we have not over-written the border property for the logo, so the border will continue to show on mobile devices. Simple isn't it?

Linking to Different Stylesheets Using Media Queries

Adding all the styles in the same CSS file is acceptable for the above example, but for a full-fledged website, it will become a pain to manage the code. That is why I prefer to link a new stylesheet for specific screen sizes. The way to do that is to use the media attribute of the link tag.

<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobile-device.css" />

Now you can define all the mobile specific styles in the mobile-devices.css file.

How to Test Multiple Devices?

Being able to style your website for various devices is one part of the problem. You need to be able to test too. If you are a proud owner of an iPhone, an android device, an iPad etc, then you're can test it on each of these devices directly. For the rest of us, there is a brilliant site called ProtoFluid. It allows you to enter a URL (which can be a local URL too) and it renders the page as if it were being viewed on the browser of an iPhone, iPad and a wide variety of devices. Another huge advantage of using ProtoFluid is that it allows you to use Firebug on your site. Being able to use Firebug will hugely speed up the development process.


Media query is a powerful tool in a world where websites are viewed on a huge range of devices. With very little change, you can make an existing website mobile and tablet compliant. Today, when building a new website, many developers build it for the desktop screen and then use media queries to retro-fit it for the mobile and tablet. While this will work, its not the optimal way to do it. Media queries are meant for design presentation, not optimization. To optimize for the mobile, you have to optimize pictures and the markup.

The English architect Christopher Wren once quipped that his chosen field “aims for Eternity,” and there’s something appealing about that formula: Unlike the web, which often feels like aiming for next week, architecture is a discipline very much defined by its permanence.


A building’s foundation defines its footprint, which defines its frame, which shapes the facade. Each phase of the architectural process is more immutable, more unchanging than the last. Creative decisions quite literally shape a physical space, defining the way in which people move through its confines for decades or even centuries.

Working on the web, however, is a wholly different matter. Our work is defined by its transience, often refined or replaced within a year or two. Inconsistent window widths, screen resolutions, user preferences, and our users’ installed fonts are but a few of the intangibles we negotiate when we publish our work, and over the years, we’ve become incredibly adept at doing so.

But the landscape is shifting, perhaps more quickly than we might like. Mobile browsing is expected to outpace desktop-based access within three to five years. Two of the three dominant video game consoles have web browsers (and one of them is quite excellent). We’re designing for mice and keyboards, for T9 keypads, for handheld game controllers, for touch interfaces. In short, we’re faced with a greater number of devices, input modes, and browsers than ever before.

In recent years, I’ve been meeting with more companies that request “an iPhone website” as part of their project. It’s an interesting phrase: At face value, of course, it speaks to mobile WebKit’s quality as a browser, as well as a powerful business case for thinking beyond the desktop. But as designers, I think we often take comfort in such explicit requirements, as they allow us to compartmentalize the problems before us. We can quarantine the mobile experience on separatesubdomains, spaces distinct and separate from “the non-iPhone website.” But what’s next? An iPad website? An N90 website? Can we really continue to commit to supporting each new user agent with its own bespoke experience? At some point, this starts to feel like a zero sum game. But how can we—and our designs—adapt?

A flexible foundation

Let’s consider an example design. I’ve built a simple page for a hypothetical magazine; it’s a straightforward two-column layout built on a fluid grid, with not a few flexible images peppered throughout. As a long-time proponent of non-fixed layouts, I’ve long felt they were more “future proof” simply because they were layout agnostic. And to a certain extent, that’s true: flexible designs make no assumptions about a browser window’s width, and adapt beautifully to devices that have portrait and landscape modes.

But no design, fixed or fluid, scales seamlessly beyond the context for which it was originally intended. The example design scales perfectly well as the browser window resizes, but stress points quickly appear at lower resolutions. When viewed at viewport smaller than 800×600, the illustration behind the logo quickly becomes cropped, navigation text can wrap in an unseemly manner, and the images along the bottom become too compact to appear legible. And it’s not just the lower end of the resolution spectrum that’s affected: when viewing the design on a widescreen display, the images quickly grow to unwieldy sizes, crowding out the surrounding context.

In short, our flexible design works well enough in the desktop-centric context for which it was designed, but isn’t optimized to extend far beyond that.

Becoming responsive

Recently, an emergent discipline called “” has begun asking how physical spaces can respond to the presence of people passing through them. Through a combination of embedded robotics and tensile materials, architects are experimenting with art installations and wall structures that bend, flex, and expand as crowds approach them. Motion sensors can be paired with climate control systems to adjust a room’s temperature and ambient lighting as it fills with people. Companies have already produced “smart glass technology” that can automatically become opaque when a room’s occupants reach a certain density threshold, giving them an additional layer of privacy.

In their book Interactive Architecture, Michael Fox and Miles Kemp described this more adaptive approach as “a multiple-loop system in which one enters into a conversation; a continual and constructive information exchange.” Emphasis mine, as I think that’s a subtle yet powerful distinction: rather than creating immutable, unchanging spaces that define a particular experience, they suggest inhabitant and structure can—and should—mutually influence each other.

This is our way forward. Rather than tailoring disconnected designs to each of an ever-increasing number of web devices, we can treat them as facets of the same experience. We can design for an optimal viewing experience, but embed standards-based technologies into our designs to make them not only more flexible, but more adaptive to the media that renders them. In short, we need to practice responsive web design. But how?

Meet the media query

Since the days of CSS 2.1, our style sheets have enjoyed some measure of device awareness through . If you’ve ever written a print style sheet, you’re already familiar with the concept:

In the hopes that we’d be designing more than neatly formatted page printouts, the CSS specification supplied us with a bevy of acceptable media types, each designed to target a specific class of web-ready device. But most browsers and devices never really embraced the spirit of the specification, leaving many media types implemented imperfectly, or altogether ignored.

Thankfully, the W3C created as part of the CSS3 specification, improving upon the promise of media types. A media query allows us to target not only certain device classes, but to actually inspect the physical characteristics of the device rendering our work. For example, following the recent rise of mobile WebKit, media queries became a popular client-side technique for delivering a tailored style sheet to the iPhone, Android phones, and their ilk. To do so, we could incorporate a query into a ed style sheet’s attribute:

The query contains two components:

  1. a media type (), and
  2. the actual query enclosed within parentheses, containing a particular () to inspect, followed by the target value ().

In plain English, we’re asking the device if its horizontal resolution () is equal to or less than . If the test passes—in other words, if we’re viewing our work on a small-screen device like the iPhone—then the device will load . Otherwise, the is ignored altogether.

Designers have experimented with resolution-aware layouts in the past, mostly relying on JS-driven solutions like Cameron Adams’ excellent script. But the media query specification provides a host of media features that extends far beyond screen resolution, vastly widening the scope of what we can test for with our queries. What’s more, you can test multiple property values in a single query by chaining them together with the keyword:

Furthermore, we’re not limited to incorporating media queries in our s. We can include them in our CSS either as part of a rule:

Or as part of an directive:

But in each case, the effect is the same: If the device passes the test put forth by our media query, the relevant CSS is applied to our markup. Media queries are, in short, conditional comments for the rest of us. Rather than targeting a specific version of a specific browser, we can surgically correct issues in our layout as it scales beyond its initial, ideal resolution.

Adapt, respond, and overcome

Let’s turn our attention to the images at the base of our page. In their default layout, the relevant CSS currently looks like this:

I’ve omitted a number of typographic properties to focus on the layout: Each element is sized at roughly one third of the containing column, with the right-hand margin zeroed out for the two pictures at the end of each row (). And this works fairly well, until the viewport is either noticeably smaller or wider than our original design. With media queries, we can apply resolution-specific spotfixes, adapting our design to better respond to changes in the display.

First of all, let’s linearize our page once the viewport falls below a certain resolution threshold—say, . So at the bottom of our style sheet, let’s create a new block, like so:

If you view our updated page in a modern desktop browser and reduce the size of your window below , the media query will disable the floats on the design’s major elements, stacking each block atop each other in the document flow. So our miniaturized design is shaping up nicely, but the images still don’t scale down that intelligently. If we introduce another media query, we can alter their layout accordingly:

Don’t mind the unsightly percentages; we’re simply recalculating the widths of the fluid grid to account for the newly linearized layout. In short, we’re moving from a three-column layout to a two-column layout when the viewport’s width falls below , making the images more prominent.

We can actually take the same approach for widescreen displays, too. For larger resolutions, we could adopt a six-across treatment for our images, placing them all in the same row:

Now our images are working beautifully at both ends of the resolution spectrum, optimizing their layout to changes in window widths and device resolution alike.

But this is only the beginning. Working from the media queries we’ve embedded in our CSS, we can alter much more than the placement of a few images: we can introduce new, alternate layouts tuned to each resolution range, perhaps making the navigation more prominent in a widescreen view, or repositioning it above the logo on smaller displays.

But a responsive design isn’t limited to layout changes. Media queries allow us to practice some incredibly precise fine-tuning as our pages reshape themselves: we can increase the target area on links for smaller screens, better complying with Fitts’ Law on touch devices; selectively show or hide elements that might enhance a page’s navigation; we can even practice responsive typesetting to gradually alter the size and leading of our text, optimizing the reading experience for the display providing it.

A few technical notes

It should be noted that media queries enjoy incredibly robust support among modern browsers. Desktop browsers such as Safari 3+, Chrome, Firefox 3.5+, and Opera 7+ all natively parse media queries, as do more recent mobile browsers such as Opera Mobile and mobile WebKit. Of course, older versions of those desktop browsers don’t support media queries. And while Microsoft has committed to media query support in IE9, Internet Explorer currently doesn’t offer a native implementation.

However, if you’re interested in implementing legacy browser support for media queries, there’s a JavaScript-tinted silver lining:

  • A jQuery plugin from 2007 offers somewhat limited media query support, implementing only the and media properties when attached to separate elements.
  • More recently, css3-mediaqueries.js was released, a library that promises “to make IE 5+, Firefox 1+ and Safari 2 transparently parse, test, and apply CSS3 Media Queries” when included via blocks. While very much a 1.0 release, I’ve personally found it to be quite robust, and I plan to watch its development.

But if using JavaScript doesn’t appeal, that’s perfectly understandable. However, that strengthens the case for building your layout atop a flexible grid, ensuring your design enjoys some measure of flexibility in media query-blind browsers and devices.

The way forward

Fluid grids, flexible images, and media queries are the three technical ingredients for responsive web design, but it also requires a different way of thinking. Rather than quarantining our content into disparate, device-specific experiences, we can use media queries to progressively enhance our work within different viewing contexts. That’s not to say there isn’t a business case for separate sites geared toward specific devices; for example, if the user goals for your mobile site are more limited in scope than its desktop equivalent, then serving different content to each might be the best approach.

But that kind of design thinking doesn’t need to be our default. Now more than ever, we’re designing work meant to be viewed along a gradient of different experiences. Responsive web design offers us a way forward, finally allowing us to “design for the ebb and flow of things.”

Get our latest articles in your inbox.Sign up for email alerts.

100 Reader Comments

Load Comments

More from ALA

We Write CSS Like We Did in the 90s, and Yes, It’s Silly

Web development has changed over the past 20 years, but when it comes to writing CSS, we’re still stuck in the 1990s.


Owning the Role of the Front-End Developer

How one developer goes beyond code and fights for a seat at the table.

Process ·

Discovery on a Budget: Part II

Resources may be limited, but that doesn’t mean you have to drop the all-important discovery phase when planning a new venture.

User Research ·

My Accessibility Journey: What I’ve Learned So Far

Manuel Matuzovic explains why and how to up your accessibility game.

Accessibility ·

Design Like a Teacher

Aimee Gonzalez reflects on a difficult user migration project that led to a dramatic shift in how she approaches her work.

Interaction Design ·

CSS: The Definitive Guide, 4th Edition

We’re pleased to offer this selection from CSS: The Definitive Guide, 4th Edition.

Categories: 1

0 Replies to “Essay On Media Css Query”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *