logo

CSS Mediaqueries

August 23rd, 2011

The CSS3 module that defines media queries reached the Candidate Recommendation stage last Summer and offers introspection into the browsing environment based on the following factors:

  • browser dimensions (width, height and aspect-ratio)
  • device dimensions (device-width, device-height and device-aspect-ratio)
  • browser orientation
  • colour information (color, color-index and monochrome)
  • device-specific details such as its resolution, whether its display is grid or bitmap-based, and the scan type (progressive or interlaced … applicable to televisions)

Not all of these properties are currently supported, but many are. Additionally, most of them support min and max prefixes like the one used belowe, enabling you to tailor your queries very specifically.

@media screen and (max-width:480px) {
background-color:red;
font-size:1.5em;
}

This set of styles is only applied to a screen which is 480 pixels wide or less.

A mediaquery test capabilities, not individual devices or browsers, so it’s future proof. There is no redirection to a different page, it’s one page for all. The mediaquery is tested before any assets are downloaded, saving bandwith and speeding up the display.

Some useful tutorials about mediaqueries are listed hereafter :

screen.width & screen.height for iOS devices

August 16th, 2011

You can detect the screen dimensions of a web device via JavaScript by using screen.width and screen.height.

For an iPad one would think that screen.width would be 768 when being held vertically and 1024 when held horizontally. However, screen.width is always 768 regardless of the way you’re holding the iPad; likewise, screen.height is always 1024. The same is true for the iPhone/iPod Touch. screen.width is always 320 and screen.height is always 480.

The iOS devices support however the window.orientation property, so if necessary, you can use that to determine if the user is in horizontal or vertical mode.

  • window.orientation is 0 when being held vertically
  • window.orientation is 90 when rotated 90 degrees to the left (horizontal)
  • window.orientation is -90 when rotated 90 degrees to the right (horizontal)

There is also the orientationchange event that fires on the window object when the device is rotated.

The mediaquery “orientation” works also in current versions of Safari and Firefox on a desktop machine. Simply change the size of your browser window until the height is longer than the width and you get “portrait”.

CSS Positioning

August 12th, 2011

The layout properties available in CSS are :

  • position : static
  • position : relative
  • position : absolute
  • position : fixed
  • float : left or float : right

The default positioning for all elements is position:static; the element is not positioned and occurs where it normally would in the document. With position:relative, elements are moved relative to where it would normally occur in the document with the parameters top, bottom, right or left. With position:absolute, the element is removed from the document and placed exactly where the parameters top, bottom, right or left tell it to go.

A combination of a relative and absolute positionned div’s allows to make a two-column layout. An advantage to using absolute positioning is that we can position the elements in any order on the page, regardless of the order they appear in the HTML. A disadvantage is that other elements are obscured by the absolutely positioned elements. This can be avoided if a fixed height is set on the absolute positionned elements, but if the text displayed in this element is longer or the font size is changed, new problems appear. A better solution for variable height columns is to float an element to push it as far as possible to the right or to the left, and allow text to wrap around it. Two elements floated to the same side will push up against each other. To push down the rest of the content the floats can be cleared after the floating elements.

Position:fixed behaves like position:absolute, but it will position an element in reference to the browser window as opposed to the web page. Fixed elements should stay exactly where they are on the screen even when the page is scrolled.

There is a divide between web designers saying you should use absolute positioning and web designers saying you should use floats, both claiming that the other method breaks faster. Both are right, it depends on the situation. There is a simple rule :

If elements should not interact, use absolute positioning, if they should, use floats.

Another benefit of floats is the progressive downloading; as the text is loaded it is displayed onto the page immediately.

Links to examples of layouts with different positionned elements are listed hereafter ( look at the sourcecode of the webpages to view the CSS code) :

Links to some useful tutorials about CSS positioning are shown in the following list :

Responsive, adaptive and reactive webdesign

August 8th, 2011

Responsive web design is creating web layouts that can adapt to a multitude of displays and devices. Using this technique, you can eliminate the need to create device-centric designs and allow your content to be displayed from a single source, on an unlimited number of mediums.

Web designers often transform their desktop layouts into something optimized for devices with smaller screens by adding additional javascript and additional css code. That’s not the right solution for mobile devices with less powerful CPU’s and slower network connections where speed and low roaming charges matters more than on desktop PC’s. Simply resizing the same application to fit on multiple devices doesn’t necessarily ensure the best experience for users.

The main objective of responsive web design is to load only those files to the device which are really displayed and to minimize the file size of the downloaded elements, including images. Responsive web design is the practice suggesting that design and development should respond to the user’s behavior and environment based on screen size, platform and orientation. Adjusting images to make them context-aware, according to the different screen widths or devices is another important aspect of responsive web design. To achieve this you can combine  two methods : image resizing (shrinking) in a first step and cropping if it get below a specific size.

The pioneer of responsive web design is Ethan Marcotte, a web designer, developer, speaker and author, living in in Boston, Massachusetts. His blog is called Unstoppable Robot Ninja.

The technical ingredients for responsive web design are :

  • fluid grids
  • media queries
  • flexible images
  • viewport settings

Some web designers prefer the term adapative instead of responsive for these technologies, other call it reactive.

A recommended approach to start with responsive web design is to start with a mobile first layout. You have to keep in mind that most internet users do not keep a browser open full screen. Another issue to care for is caching, mainly if images of different sizes with the same name are used.

Links to some useful documentation about responsive web design and context-aware images are shown in the following list :

Scroll content on the iPhone and iPad

July 29th, 2011

To scroll content inside a fixed width-height element (e.g. div) on an iPhone or iPad, the user must use two fingers to scroll any area on a page that is not the entire page. One way to work around this ‘feature’ is to implement a touch event handler that moves the div up when the user touches it.

A better way to add one finger scrolling to divs on iPhone’s and iPad’s is the iScroll4 script developed by Matteo Spinelli. This script provides the following features :

  • Pinch / Zoom
  • Pull up/down to refresh
  • Improved speed and momentum
  • Snap to element
  • Customizable scrollbars

Initializr – HTML5 templates generator

July 25th, 2011

Initializr has been created by Jonathan Verrecchia to help the spread of HTML5 on the web.

Jonathan Verrechia is a french Web Developer, Author and Blogger working at SFEIR on HTML5 and CSS3. He is the author of the french book HTML5 – De la page web à l’application web, together with Jean-Pierre Vincent.

Initiallizr is a HTML5 templates generator whicht is built on HTML5 Boilerplate, a powerful HTML5 template created by Paul Irish and Divya Manian.

HTML CSS Box Model

June 16th, 2011

HTML CSS Box Model

All HTML elements can be considered as boxes. The CSS box-model is shown in the figure at left.

The width and height properties specified for an element with CSS refers only to the content area. To get the full size of the element, you must also add the padding, the border and the margin.

 

 

 

The different parts are :

  • Margin : transparent area around the border
  • Border : a border around the padding and content with a border color
  • Padding : clears an area around the content with the background color of the box
  • Content : where text and images appear

 

Advanced stuff about CSS selectors

June 12th, 2011

A CSS selector is made up of a pattern that is matched against all elements in the document tree, it’s the part that comes before the opening curly brace. The selector types are :

  • Universal : *  (Matches any element)
  • Type :  p  (Matches  element p)
  • Class :  .info (Matches any element whose class attribute contains the value info)
  • ID : #temp (Matches any element with an id equal to temp)
  • Descendant : p b (Matches any b element that is a descendant of an p element)
  • Child : p > b (Matches any b element that is a child of an p element)
  • Adjacent : p + b (Matches any b element immediately preceded by a sibling element p)
  • Attribute : p[att condition] (Matches any p element whose att attribute is compliant to the condition)
  • Pseudo-Class : p:action (Matches p during certain  actions; pseudo-classes are first-child, link, visited, active, hover, focus, lang(cc))
  • Pseudo-Element : p:content (Matches p for certain contents; pseudo-elements are first-line, first-letter, before, after)

Selectors can be grouped and combined :

  • Multiple class selectors :p.info.error {color:#900;font-weight:bold;}(Matches p elements which have both “info” and “error” in their list of class names)
  • Descendant selectors :div#temp li p.info { color:#f00; }(Matches all p elements with a class name of “info” that are contained by an li element that is contained by a div element with the id “temp”)
  • Child selectors :p > strong { color:red }(Matches all strong elements that are children of a p element)
  • Adjacent siblings selectors :p + p { color:green }(Matches an element p which is the next sibling p to the first element)
  • Grouping :#my1, #my2,  #my3 {color:blue}(Matches all elements with the id’s my1, my2 and my3)
  • Attributes selectors :p[lang|=en] { color:yellow }(Matches all elements whose lang attribute starts with “en”)

:before and :after

The :before and :after pseudo-elements can be used to insert generated content before or after an element’s content.

3 digit color hex codes:

The 3 digit only hex codes are shorthand for the codes that have the numbers repeated in pairs.

#06C = #0066CC

z-index:

The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). An element with a negative value is displayed behind any with an undefined or positive z-index value in the same stacking context.

Some useful links about CSS are :

Internet Explorer Conditional Comments

June 2nd, 2011

last update : 3 September 2011
Conditional comments are a simple Internet-Explorer-only feature that Microsoft added to IE5 Windows and later. They provide an easy way to detect what IE browser a visitor is using to serve him different blocks of HTML.

There are two types of conditional comment: downlevel-hidden and downlevel-revealed. Downlevel-hidden comments hide HTML from non-IE browsers and from down-level IE browsers. The basic syntax of a downlevel-hidden conditional comment is :

<!--[if expression]> HTML <![endif]-->

expression can contain a number of different operators and values.

The downlevel-revealed conditional comment enables you to include content in browsers that do not recognize conditional comments. The basic syntax is :

<![if expression]> HTML <![endif]>

Conditional comments are usually used to load specific css or javascript files.

Conditional comments produce valid W3C code.

Viewports for mobile devices and tablet PC’s : a pixel is not a pixel

April 20th, 2011

last update : 30 August 2011
Designing a webpage which looks good on desktop PC’s, mobile devices and tablet PC’s is challenging. You have to optimize your content at least for screens that are 320px, 480px, 768px, and 1024px wide. One tool to reach this goal is the viewport meta tag.

The viewport meta tag was introduced by Apple for the iPhone, and it has since been picked up by Microsoft for Windows Mobile and Nokia for Maemo. The tag is ignored by regular desktop browsers.

<meta name="viewport" content="width=800" />

Mobile Safari presents desktop-sized websites on small screens by rendering to a virtual browser screen that is 980 pixels wide. Opera assumes a page to be 850 pixels wide. Pages on the iPad in portrait mode and on other mobile devices are scaled down.  Pages can be zoomed and panned. Viewport tags tell the Mobile Safari that the website displays properly narrower than 980 pixels. The webpage can be set for other scaling preferences.

Apple suggests to avoid hard-coding a width for the viewport and to use the physical device-width to set the viewport :

<meta name="viewport" content="width=device-width" />

This setting makes one CSS pixel equal to one device pixel. The physical device-width refers to the screen size in portrait mode. One problem is that the content is blowed up if the device is oriented in landscape mode. To avoid blow-up, a maximum scale factor can be applied :

<meta name="viewport" content="width=device-width, maximum-scale=1.0" />

You can add the attribute “user-scalable=no” to disable the pinch-to-zoom feature :

<meta name="viewport" content="width=device-width, user-scalable=no" />

This is useful for preventing accidental zooms and makes web apps feel more app-like, but most users might want to see the content at a larger size.

The complete list of viewport properties for iPad (and iPhone with Retina display) is given below :

  • width : 200 – 10.000 ; default : 980
  • height : 223 – 10.000
  • minimum-scale : 0.0 – 10.0 ; default : 0.25
  • maximum scale : 0.0 – 10.0 ; default : 1.6
  • initial-scale : between min and max
  • user-scalable : yes / no ; default : yes

To hide the control-bar which consumes about 60 pixels, the following script can be used :

<body onload="setTimeout(function() { window.scrollTo(0, 1) }, 100);"></body>

To deal with the greatly differing screen sizes, CSS media queries allow to specify completely different stylesheets depending on how large the screen is.

<link media="only screen and (max-device-width: 480px)" href="small.css" type= "text/css" rel="stylesheet">
<link media="only screen and (min-device-width: 481px) and (max-device-width: 1024px)" href="medium.css" type="text/css" rel="stylesheet">
<link media="screen and (min-device-width: 1025px)" href="large.css" type="text/css" rel="stylesheet">

Instead of using separate css-files, the media query can be used inside a single css-file :

@media only screen and (min-device-width: 481px) and (max-device-width: 1024px)
{
styles
}

In fact it’s useful to consider two viewports : one based on device pixels, the other based on CSS pixels. Only at zoom level 100% one CSS pixel is exactly equal to one device pixel.

The iPhone 4’s Retina display has a far larger physical pixel density than previous iPhones. Still, it reports 320px for the device-width media query (as well as JavaScript screen.width) both with and without the meta viewport width=device-width.

A few links about useful tutorials about viewports and other related subjects are listed herafter :

The next list shows links to iPad and iPhone simulators to test the rendering of webpages on these devices :