Tech That!

The rantings of a mad scientist

Posts Tagged ‘introduction

A quick introduction to CSS

leave a comment »

Before I dig into the CSS 3 draft, I am going to give a quick introduction to the basics of CSS for those who do not feel entirely comfortable with the apparent complexity of Cascading Style Sheets;

First of all, what is CSS? CSS is a programming language, or perhaps more of a file syntax, for styling for XML and HTML.

But can’t I do that with HTML tags? Well, you can, but there are two reasons why you should not do that: (1) The standard dictates that you should separate the styles from the content and structure, and (2) Not all browsers support the same HTML tags, and style them in the same way. CSS gives you a powerful toolkit for making the page look exactly how you want it to.

First of all, you must realize that with the versatility of CSS comes complexity, and if you start your CSS career by digging into the stylesheets of a large site, you will most likely be very confused at first. Therefore, let us start with the basics:

CSS from the bottom up

There are several ways to style your web pages through CSS: inline styles, internal style definitions and external stylesheets, where the last one is the recommended and most used one. I will come to why later.

Inline styles are styles set directly in one element through the style=”" attribute like this: <span style=”color: red;”> ( this would make the encapsulated text in the span red )

Internal style definitions are defined inside <style type=”text/css”><style> tags in the HTML or XML document, and uses selectors ( I will explain the syntax of CSS later ) to style given elements.

And external stylesheets consist of “pure” CSS in an external file that is included through a link tag as such: <link rel=”stylesheet” type=”text/css” href=”stylesheet.css” />

I encourage the use of external stylesheets, because they allow you to share the same styles between several pages ( they all just need the same link tag ), and make it very easy to do site-wide design changes by only editing a single file. Secondly, external stylesheets can be compressed quite easily, and several stylesheets can be combined on any given page to provide styles from different sources.

Getting down and dirty – selectors and styles

The syntax of CSS itself consists of two parts, selectors and styles. The selectors tell the browser what elements the styles should apply to, and the styles tell how the elements should look.

Selectors

CSS primarily has six types of selectors, though this will likely be expanded in the future:

  • element
  • id
  • class
  • decendency
  • attribute
  • pseudo-classes

The element tag is the simplest one, as it simply specifies the type of the elements that should be styled, and applies the styles to all of the elements on the page that matches. One such selector could be something as simple as “p” or “strong” . These two selectors would match p-tags and strong-tags respectively.

Next, we have the id selector. This allows you to apply styles to only the element with a given value in its ID attribute. The id selector is also quite simple; a hash sign ( # ), followed by the id of the element you wish to style. For instance, “#myelement” would match the element on the page with the id “myelement”

The class selector allows you to apply styles to a group of elements on the page that share the same HTML class on your page. In syntax, it is similar to the id selector, but it uses a period ( . ) instead of the hash sign ( # ). Matching all elements with the class “myclass” would thus be done by using the selector “.myclass”

Decendency selectors allow you to tell the browser to only apply styles that match a given selector inside an element that matches another. If I wanted to style all anchor ( a ) tags inside elements with class “linkme”, I could do this in CSS by using the decendency selector ( it is not really a selector, but more of a way to combine other selectors ) which is, quite simply, a space. The correct selector would then be “.linkme a”. Not too bad is it?

We can also filter on the contents of specific attributes in CSS, though not all browsers support this feature. Specifying attribute selectors is a bit trickier than the previous selectors, but they are very powerful once you learn how to use them properly. An attribute selector consists of an attribute ( such as href, rel, title, class or id ), a comparison operator, and a value, contained in a pair of square brackets []. There are several comparison operators, but the most commonly used ones are:

  • =, the contents of the attribute has to match exactly the value you give
  • ~=, at least one of the space-separated words of the attribute has to match the value you give
  • |=, same as above, but hypen-separated
  • no comparison operator or value, the attribute has to exist on the element

The value may be encapsulated with double quotes, but this is not required. If I wanted to match all anchor elements linking to youtube for instance, I could do the following: [href=http://www.youtube.com]

And finally, we have the pseudo-class selector. This allows you to select only elements that have a certain property or state. Say you wanted to style a link only when the user hovers over it, you would use the :hover pseudo-class selector to accomplish this. There are several of these, and more will come with CSS3, and support varies greatly between browsers, but the most common ones are:

  • :hover – when the user hovers over the element
  • :visited – if the user has visited the element ( mostly used on links )
  • :first-child – matches only if the element is the first child node of the parent
  • :first-letter – matches the first letter of the text content of the element

If we wanted to turn a link bold when it is hovered over, we would typically do something like the following: “a:hover { font-weight: bold; }”

There are two things that might confuse you with my last example, one is the fact that I put an a before the colon, and the second is the statement “font-weight: bold”. The last one I will come back to when discussing styles, but the first one deserves an explanation straight away.

A common issue one might encounter is, like above, that you want to style the hover styling on all anchor elements. However, if we had simply written “:hover”, that would match all the elements on the page, which would mean that everything on the page would turn bold when hovered over. Therefore, CSS allows you to chain several selectors together to allow for more specific filter. This is done by simply appending one selector to another without any space in between. The above example therefore translates to ” select all a elements when they are hovered over”, whereas “:hover” would mean “select any element that is hovered over”. See the difference? There are no limits here, and you could even do something like this: “a.coollink:hover:first-letter”, which would style the first letter of all anchor elements with the class “coollink” when they are hovered over.

If we describe this chaining as a “and” operation, since it requires that the element matches all of the chained selectors, we soon find ourselves in need of a similar “or” operator. Luckily, CSS provides this as well, the comma. If I wanted a style to apply to, for example, all anchor elements and all strong tags with the class “styleme”, I could do that like this: “a, strong.styleme”. Due note: The comma is an absolute separator, and as such, “div a, strong” would not match all a’s and strong’s inside a div, but rather all elements that are either a’s inside a div OR are simply strong tags!

What about the styles?

As mentioned, CSS consists of styles and selectors, and whereas there are quite few selectors, there is a vast amount of styles.

A style takes the form of “attribute: value;”, and you may specify multiple styles for each selector. The way the styles are specified follows the following syntax:

selector1, selector2, selector3 {
  attribute1: value1;
  attribute2: value2;
  attribute3: value3;
  /* Comment: etc... */
}

For a full list of CSS attributes, I suggest you have a look at the following page: http://www.w3schools.com/CSS/CSS_reference.asp, but I will mention a few of the most common ones:

  • font-family – Specifies the font(s) to use for the specified elements
  • font-size – The size of the text
  • color – The text color
  • background – Background styling ( color, images, etc… )

Again, the styles are so diverse and plentiful that the best way to learn is by deciding on a design, and then simply try to create it from scratch, and learn by looking things up as you go. Experience is the best teacher one can have.

So, there you have it. A quick and dirty introduction to CSS that has hopefully provided some insight into the wonderful world of website styling. The only thing that remains now is to start using it, and to set challenges for yourself that require a bit more knowledge than you have. That way, you will be forced to look up how other have done it, and expand your knowledge much faster than any tutorial can do.

Written by Jon Gjengset

October 1, 2009 at 17:41

The prospects of HTML 5

leave a comment »

As a webdeveloper, feature additions and updates to commonly used libraries and languages are always exciting. Unfortunately, there is one core language of web development which has not received a proper update in years – HTML. Sure, we had XHTML, but in my opinion, that was more of a structural change than it was a rewrite of HTML. XHTML merely enforced a XML structure as well as standardize the elements used for various types of content.

This is all about to change with the development of HTML 5. HTML 5 is currently only a W3C draft, but some of its major features are already implemented in various browsers. As supposed to XHTML, HTML 5 aims to bring HTML into this century, and make it more flexible in order to satisfy the needs of today’s developers and users for multimedia content, AJAX-based user interfaces, geolocation and desktop application-like behaviour.

Brief overview of new features

HTML 5 provides a plethora of extensions and changes to traditional HTML, and to get a complete overview I suggest your read the W3C Draft which makes for very interesting reading once you can look past the RFC style. There are however a couple of features that are especially interesting:

  • The whole language will be based on DOM definitions, which makes the border between Javascript and the HTML quite a lot thinner.
  • HTML 5 attempts to discard the remaining style-based tags of HTML, as well as remove support for frames and other “ugly” practices
  • It is also developed to accommodate the way modern websites are structured, and make the structure more available to computer interpretation. For instance, instead of using divs for all sorts of site content, HTML 5 introduces specialized tags for the different sections of a webpage such as:
    • <header>
    • <footer>
    • <article>
    • <aside>
    • <menu>
    • <section>
  • A new way of handling element contexts ( i.e. moving away from the differentiation of inline and block context )
  • Native Drag-and-drop and Copy-Cut-Paste APIs
  • Undo history and editable content
  • Support for geolocation-enabled applications
  • Native multimedia tags and players to avoid the format challenges developers currently face when adding multimedia to their sites

There are several more, but again, I recommend having a look at the W3C Draft for a more in-depth description.

Multimedia

HTML 5 introduces two especially interesting tags: <audio> and <video>. These tags are quite simple, but very powerful. They both require nothing but a source file to play, but they not only provide a native, integrated player for the given content format, but it also provides a scriptable API to manipulate the controls and playback from a scripting language like Javascript. No more proprietary or hard-to-customize flash players with limited format support!

Draggable, copy-paste and undo

The draft also introduces two new concepts that are still under heavy debate with regards to the implementation: Native drag-and-drop support and a copy-paste API as an extension of the draggable support ( since according to the draft, you “drag” the copied content into the clipboard, and “drop” it back from the clipboard ), and an undo-redo history API.

The draggable support will remove the need for a third-party drag-n-drop library such as jQuery-UI, mootools or Prototype, and let the browser deal with this directly. Not only will this probably provide a smoother user experience, but it will most certainly enable you to build more flexible UIs since the W3C Draft dictates a lot of event triggers and intermediate controls that let you handle the dragging in high detail.

Undo history is probably the most controversial feature of the W3C Draft as no good standard definition of it has been found. From the draft one can nonetheless extract some useful indicators of how the final feature will work.

According to the current definition, the undo/redo history will store all changes to the website DOM, and allow the user to revert to previous version of the page. Most probably, it will also allow control hooks that enable you to do server actions when the user walks backwards or forwards through the history.

So, you might ask, why would I need DOM history? Well, both because you will now be able to use AJAX page loading without breaking the back button, but also because of the new attribute “contentEditable”:

Editable HTML content

HTML 5 brings a seemingly innocent attribute called “contentEditable” which, when enabled, allows the user to directly manipulate the DOM through for instance a rich-text editor, or however the browser developers decide to implement the feature. This makes for a whole new type of webpages where you can let the user completely redesign the site to his or her own liking, and where the changes may be saved for later use. And just imagine the advantages with regards to rich-text editing for blogs, articles, or indeed any other web content.

Geolocation

A new API has also been deviced to encourage the use of websites for portable devices or other GPS enabled computers. The API allows the website to read the users current location, as well as any updates to this. This will also enable developers to build applications that are location-sensitive, and give you data relative to your location.

Other scripting changes

With HTML 5, W3C has also had a look at commonly requested features and features implemented by the major Javascript frameworks. This has lead to the standardization of certain long sought-after components like:

  • getElementsByClassName
  • Input fields with native validation support ( type=”date, datetime, email, url, telephone…”, the “required” attribute, etc )
  • Support for unlimited additional attributes for internal use as long as they are prefixed by data-
  • Independent inputs – input fields may be placed outside a form tag, but still linked to the form itself
  • Client-side storage – a simple key/value-pair local database accessible through Javascript which will probably bring a great deal more offline web applications
  • The progress/meter tags – A way of visualizing progress or numerical values to the user without the use of ugly table/css hacks.
  • Anchor ping attribute – This new attribute allows you to specify a list of URLs that should be pinged if the user clicks a link to avoid redirects to log link clicks, and make them asynchronous instead.
  • The canvas tag

The <canvas> tag is also a very promising new feature, that enables developers to draw directly to the users screen. This makes way for Javascript-based games, handwriting-enabled applications, Javascript movies, and who knows what else. If you’re running Chrome ( Firefox and Opera also work, but cause a great deal of lag ), you can have a look at the kind of things that can be done at http://www.chromeexperiments.com/.

So, when can I use it?

Since HTML 5 is aimed at being backwards compatible, you can start to implement it today, though many users will probably not receive the full experience of the markup in a while. A good reference might be molly.com’s  A Selection of Supported Features in HTML5. You might also want to make use of the Javascript HTML 5 detection library Modernizr.

What about CSS 3?

CSS 3, however amazing it might be, is not a part of the HTML 5 standard. Also, support for this the CSS 3 Draft is not very broad either. I will probably post an overview of it at a later date as well.

Further reading and sources:

http://dev.w3.org/html5/html4-differences/

http://www.smashingmagazine.com/2009/07/16/html5-and-the-future-of-the-web/

Geolocation: http://dev.w3.org/geo/api/spec-source.html

http://www.w3.org/TR/html5/forms.html

http://www.w3.org/TR/html5/video.html

http://www.w3.org/TR/html5/semantics.html

The full spec: http://www.w3.org/TR/2008/WD-html5-20080122

Written by Jon Gjengset

September 24, 2009 at 17:59

Follow

Get every new post delivered to your Inbox.