Create a responsive web site using CSS media queries

Source: Internet
Author: User
Tags ruby on rails

Designed for all screen sizes

Fixed-width static sites are quickly replaced by flexible responsive designs that scale up and down depending on the screen size. With responsive design, you can present a usable interface, no matter what device or screen you use to access the site. Responsive design responds to a variety of screen sizes, so it's also a "forward-looking" site that will evolve quickly as new smartphones and tablets emerge. The main way to implement responsive design is to use CSS media queries. In this article, we'll learn how to use media queries for desktop sites, mobile phones, and tablets.

Brief introduction

Nowadays, more mobile phones and tablets are being asked every day. Consumers have the ability to imagine a variety of specifications and shapes, but web developers face a challenge: how to make their websites look good on traditional browsers, mobile phones, and tablet browsers, and how to provide a first-class user experience on screens of all sizes, the answer is: responsive design . Responsive design can vary depending on the screen size displayed. The main way to implement responsive design is to use CSS media queries.

In this article, you'll explore how to use media queries for desktop sites, mobile phones, and tablets. You will also learn how to detect media query support and how to provide a reliable experience for browsers that do not yet support this technology.

Prerequisite

The code samples in this article have been designed to run in Web browsers that support CSS media queries, including Mozilla Firefox, Apple Safari, Google Chrome, and Opera. See Resources for a complete list of browser compatibility support that shows CSS3 media queries in desktop and mobile browsers.

Back to top of page

Responsive design

The responsive design can vary depending on the screen size displayed, and each screen it renders looks different. Responsive design provides the best results for the UI, following the available screen properties.

For example, if the site layout has a side bar that occupies 25% of the screen width, the sidebar is rendered differently on screens of different sizes. The sidebar is widescreen on a larger desktop monitor and is extremely narrow on smaller smartphone screens. On the highest or smallest screen, the sidebar is probably no longer a usable UI component.

With media queries, you can write CSS that automatically changes your design to provide the best UI experience for different screen sizes.

Back to top of page

Media Enquiry

Starting with CSS version 2, media support can be obtained through the media type in CSS. If you've ever used a plot style sheet, you've probably already used a media type. Listing 1 shows an example.

Listing 1. Working with Media types
<link rel= "stylesheet" type= "Text/css" href= "site.css" media= "screen"/><link rel= "stylesheet" type= "text/ CSS "href=" print.css "media=" print "/>

In Listing 1, the media attribute defines the style sheet that should be used to specify each media type:

    • screenApplies to the computer color screen.
    • printApplies to what you see in Print Preview mode or what your printer prints.

As part of the CSS V3 specification, you can extend the media type function and allow more precise display rules to be used in the style sheet. Media Queries are an expression that evaluates to True or False. If true, the style sheet continues to be used. If False, the style sheet cannot be used. This simple logic becomes more powerful through expressions, giving you more flexibility to use custom display rules for specific design scenarios.

A media query contains a media type followed by one or more expressions that check for specific conditions, such as the smallest screen width. The media query in the style sheet appears as shown in the example in Listing 2.

Listing 2. Media query Rules
@media all and (min-width:800px) {...}

According to the markup in Listing 2, all screens with a minimum horizontal screen width of 800 pixels (screen and print, etc.) should use the following CSS rules. The rule in the example where the ellipsis is located. For this media query:

    • @media allIs the media type, that is, applies this CSS to all media types.
    • (min-width:800px)is an expression that contains media queries, and if the minimum width of the browser is 800 pixels, it tells the browser to use only the following CSS.

Please note that in Listing 2, you can omit the keyword all and and . When a media query is applied to all media types, it is omitted all . The latter and is also optional. Rewrite the media query using the shorthand syntax, as shown in Listing 3.

Listing 3. Shorthand syntax
@media (min-width:800px) {...}

Media queries can also contain complex expressions. For example, if you want to create a style that is applied only when the minimum width is 800 pixels and the maximum width is 1200 pixels, you need to follow the rules in Listing 4.

Listing 4. Complex expressions
@media (min-width:800px) and (max-width:1200px) {...}

In your expression, you can use any number of conditions to suit your preferences and . If you want to add additional criteria to check the specific screen orientation, simply add another and keyword followed by the orientation media query, as shown in Listing 5.

Listing 5. andConditions
@media (min-width:800px) and (max-width:1200px) and (orientation:portrait) {...}

The media query in Listing 5 is activated only when the width is 800 to 1200 pixels and the orientation is portrait oriented. (Typically, the direction is meaningful only for smartphones and tablets that can easily convert the aspect mode.) If one of the conditions is False, the media query rule cannot be applied.

andThe antonym of keywords is the or keyword. andtogether, these conditions combine to form complex expressions. If one of these conditions is true, then the entire expression or two conditions that are detached are true, as shown in Listing 6.

Listing 6. orKeywords
@media (min-width:800px) or (orientation:portrait) {...}

If the width is at least 800 pixels or the orientation is vertical, the rule is applied.

Another media query keyword saved in the thesaurus is not . At the beginning of the media query, the not results are ignored. In other words, if the query not is true without a keyword, it will now be false. Listing 7 shows an example.

Listing 7. Use not
@media (not min-width:800px) {...}

In the English sense only, the code in Listing 7 shows: When the minimum width is not 800 pixels, the following CSS rules are applied. These examples simply use pixels as the unit of measure in a media query, but the units of measurement are not limited to pixels. You can use any valid CSS unit of measurement, such as cm (cm), inches (in), millimeters (mm), and so on.

Back to top of page

Useful Media Features

There are many features of the media, such as width, color, and grid, which you can use in media queries. The description of each possible media feature is not covered in this article. Documents about media queries the world Wide Web Consortium ' s (website) provides a complete list of this. (see Resources).

To design a responsive site, you only need to know some of the media features: orientation, width, and height. As a simple media attribute, the value of the direction can be portrait or landscape . These values apply to users who hold a phone or tablet, allowing you to optimize content based on two shape factors. When the height is greater than the length, the screen is considered portrait mode, and when the width is greater than the height, the screen is considered landscape mode. Listing 8 shows an orientation example of using media mode queries.

Listing 8. orientationMedia Enquiry
@media (orientation:portrait) {...}

The height and width behaviors are very similar, and are supported with min- and max- prefixes. Listing 9 shows a valid media query.

Listing 9. Height and Width Media queries
@media (min-width:800px) and (min-height:400px) {...}

If there is no min- or max- prefix, you can also use the width and height media features, as shown in Listing 10.

Listing 10. Not with min-And max-Prefix
@media (width:800px) and (height:400px) {...}

When the screen is exactly 800 pixels wide and 400 pixels high, you can use the media query in Listing 10. In reality, media queries like this may be too specific to be useful. Detecting precise dimensions is a scenario that most site visitors are not likely to encounter. Typically, a responsive design uses scopes to perform screen detection.

As a follow-up to the media query size range, the next section discusses some common media queries that you might find useful when designing a responsive web site.

Back to top of page

Common Media Queries

Most of the following media queries are based on these types of devices, as Apple has launched its first user smartphone and tablet product to the market.

If your target is a landscape-mode smartphone, use: @media (min-width: 321px) { ... }

If your target is a portrait-mode smartphone, use: @media (max-width: 320px) { ... }

If the target is a landscape-mode Apple iPad, use: @media (orientation: landscape) { ... }

If the target is portrait mode IPad, use: @media (orientation: portrait) { ... }

You may have noticed that the IPAD uses media features and is orientation used on top of width Apple's iPhone. Mainly because the IPhone does not support orientation media features. You must use to width simulate these directional breakpoints. See Resources for more information on common media features.

Back to top of page

Media queries in the SASS

The built-in support in Ruby on Rails helps propel the prevalence of syntactically Awesome Style Sheets (SASS), enabling it to rapidly strengthen in the Web development community. A detailed discussion of SASS is beyond the scope of this article, but I'll briefly cover the basics of using media queries in SASS-based style sheets. See Resources For more information about SASS.

Media queries in SASS behavior are exactly the same as in normal CSS, with one exception: they can be nested within other CSS rules. When one media query is nested within another CSS rule, the rule is placed at the top level of the style sheet, as shown in Listing 11.

Listing 11. Nested Media queries
#header {  width:400px;  @media (min-width:800px) {    width:100%;  }}

The example in Listing 11 is compiled into the code in Listing 12.

Listing 12. Compile results
#header {  width:400px;} @media (min-width:800px) {  #header {    width:100%;  }}

Back to top of page

Organize your media queries

Now that we've learned how to write media queries, it's time to consider deploying media queries into your CSS code in a logical, organized way. Determining how media queries are organized is largely a personal preference. This section explores the pros and cons of the two main approaches.

The first method is to specify a completely different style sheet for different screen sizes. The advantage is that rules can be saved in a separate style sheet, which makes the display logic clearly divided and easier for the team to maintain. Another advantage is that merging between source-code branches becomes easier. But the advantages are also shortcomings. If you want to create a separate style sheet for each media query, you cannot place all the style sheets of one element in the same folder. When you change an element in a CSS, you need to create multiple locations for viewing, which makes maintenance of the Web site CSS more difficult.

The second method is to use a media query in an existing style sheet that is next to the location where the rest of the element's style sheet is defined. The advantage of this approach is that all element styles can be saved in the same location. This can create more source code consolidation work when working in team mode, but this is a common part of all team-based software development that can be managed.

There is no so-called right or wrong method. You just have to choose the best method for your project and team.

Back to top of page

Browser support

So far, you may have believed that CSS media queries are a powerful tool and want to know which browsers support CSS media queries. Here are some good news and bad news.

    • The good news is that most modern browsers, including browsers on smartphones, support CSS media queries.
    • The bad news: Recently, the windows®internet Explorer®8 browser from Redmond does not support media queries.

      For most professional WEB developers, this means you need to provide a solution to support media queries in Internet Explorer.

The following solutions are a JavaScript polyfill named Respond.js.

Polyfill with Respond.js

Respond.js is a minimal Web browser-enhanced JavaScript library that enables browsers that would otherwise not support CSS media queries to support them. The script loops through all the CSS references on the page and parses the CSS rules using media queries. The script then monitors the browser width changes, adding or removing styles that match the media query in the CSS. The end result is the ability to run media queries on browsers that are not originally supported.

Since this is a JavaScript-based solution, browsers need to support JavaScript in order to run scripts. The script only supports the minimum and maximum media queries required to create a responsive design width . This is not a substitute for all possible CSS media queries. In the Resources section, you can read more about the features and limitations of this script.

Respond.js is one of many available open source media queries Polyfills you can choose from. If you think Respond.js can't meet your needs, after a little research, you'll find several alternatives.

Back to top of page

Conclusion

With CSS media queries, you can easily target specific screen sizes and create a reliable user experience, regardless of which browser or device you use to access your site. These technologies are a priority in responsive design, and responsive design is an emerging mobile Web design and development practice. Trying to use media queries on your site does not involve actual costs (in addition to just enhancing your existing CSS files), why not try to make it a good experience for visitors who visit your site on tablets, mobile phones or e-readers. Turn from (http://www.ibm.com/developerworks/cn/web/wa-cssqueries/)

Create a responsive web site using CSS media queries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.