html, css, jQuery, PHP, mySQL

## HTML5 Canvas and arcs of a circle: it’s a piece of Pi.

August 29th, 2011

This post is for all those confused about the use of radians when drawing circles, and arcs of circles, using the new html5 canvas element. I hope to shed some light on the subject, and give you the knowledge that you need to make use of this exciting new capability.

The radian is a measurement which describes the ratio between the length of any arc of a circle and its radius. One radian is defined as the angle subtended when the length of the arc of a circle is equal to the radius of that circle. A radian is therefore a proportion, i.e. length of the arc / radius of the arc. The symbol for radians is rad.

We know that the circumference of a circle is given by the formula 2πr, where r is the radius of the circle, and that there are 360° in a circle. Therefore:

360° = 2πr/r = 2π

In order to convert radians to degrees, it is therefore a simple matter of multiplying by 180/π. Conversely, to convert degrees to radians, multiply by π/180.

This diagram shows the angles clockwise from the position to the right of the vertex, in radians. The angles are given in 15° increments, and the degree equivalents are shown for the EAST, SOUTH, WEST and NORTH directions. (Click for larger version).

Angles of arc on a circle given in radians.

### HTML5 Canvas: arc().

The javascript arc() function allows us to draw an arc of a circle in the canvas element. Its parameters are as follows:

arc(x, y, radius, startAngle, endAngle, anticlockwise)

Where x and y are the x and y co-ordinates of the centre of the circle. The angles are drawn clockwise from the EAST, which is 0 degrees, SOUTH is 90 degrees, WEST is 180 degrees and NORTH is 270 degrees. If anticlockwise is set to true then the directions are reversed: the arc is drawn in the opposite direction.

Of course the angles given in the arc() function must be in radians, not degrees. They must also use the correct JavaScript notation:

0 = EAST

Math.PI/2 = SOUTH

Math.PI = WEST

Math.PI*3/2 = NORTH

Note the form of the notation for NORTH. This is a good example, as it shows how π is first multiplied by 3 using the * operator, and then the result is divided by 2 using the / operator. Follow this example to draw arcs that subtend any angle given in radians.

### Canvas: the context

But how do we use the canvas element? I will give a brief example where we can use the function explained above to draw slices of pie.

First add the html canvas element to your page: I have given it a size of 150px by 150px, but the default size is 300px by 150px. Make sure that you give your canvas element an id.

<canvas id=”canvas” width=”150″ height=”150″></canvas>

<script type=”application/javascript”>
function draw() {

//draw() will be called when the document loads
var canvas = document.getElementById(“canvas”);

//get the element with the id which you gave your canvas element: mine had id “canvas”
if (canvas.getContext) {
var ctx = canvas.getContext(“2d”);

//get the context: this is always an essential step. The context is then assigned to a variable.

ctx.beginPath();

//begin drawing a path

ctx.arc(75,75,50,0,Math.PI/2, false);

//change these parameters to alter the segment of circle drawn
//the first two parameters define the center of the circle
//followed by the startAngle
//then the endAngle
//finally the direction in which the arc will be drawn (clockwise=false).
//if the last parameter is changed to true, the segment will be drawn anticlockwise

ctx.lineTo(75,75);

//draw a line to the center of the circle

ctx.closePath();

//draw a line back to the arc

ctx.stroke();

//stroke the path
}
}
</script>

And there you have it! Have fun.

## CSS Gallery with z-index zoom on :hover.

August 29th, 2011

In this simple version of a CSS Gallery, an unordered list is used to contain anchor tags with thumbnails as background images. On hover, the images change to larger versions of the same files, overlying the rest of the list.

First, mark up a simple unordered list.

<ul>

<li></li><li></li><li></li>

</ul>

Now add anchor tags inside each list item, giving each one a class and id. In my example, I have skewed the thumbnails so that they look like scattered cards. I used three different classes for the three different levels of skew. If you don’t want your thumbnails to be skewed, you can give all of the anchor tags the same class. Make sure the ids are all unique! I simply numbered mine. The ids will be used to add the background images, and to change them on :hover. The markup sample below shows only the first three thumbnails: I repeated the class names for a longer list in the working example attached.

<ul>

<li><a class=”one” id=”first”></a></li>

<li><a class=”two” id=”second”></a></li>

<li><a class=”three” id=”third”></a></li>

</ul>

Now it is time for the CSS magic. Relatively position the unordered list (ul): the list items will be given a z-index on hover, and a relatively positioned parent element is essential for this to work. My unordered list has a width of 900px, a top margin of 150opx and is centred on the page using margin-left: auto and margin-right: auto, but your preferences and dimensions may vary. Experiment and see what looks most appealing to you.

The list items are then given list-style-type: none to remove the indents and bullet points, and are floated left to produce a horizontal list. The width and height match the sizes of my thumbnails: your dimensions may be different. I allowed my list items a 2px margin.

``` ul {
width: 900px;
position: relative;
margin-top: 150px;
margin-left: auto; margin-right: auto;
}
li {
list-style-type: none;
float: left;
width: 100px;
height: 128px;
margin: 2px;
}```

I will return to the list item shortly, to add a hover state. For now, add the thumbnails to the anchor tags by using their ids to give them background images. The anchor tag itself needs to be given the properties display: block and dimensions matching the thumbnail. I then added a slight box shadow:

```a {
display: block;
width: 100px;
height: 128px;
background-color: white;
border: 1px solid white;
position: relative;
}
#first {
background-image: url('birds_tn.jpg');
background-repeat: no-repeat;
background-position: 0px 0px;
}
#second {
background-image: url('dragons_tn.jpg');
background-repeat: no-repeat;
background-position: 0px 0px;
}
#third {
background-image: url('eels_tn.jpg');
background-repeat: no-repeat;
background-position: 0px 0px;
}```

Now, if you would like to add the skew to the thumbnails, add transform: rotate(deg) to the classes of the anchor tags. I also varied the z-index of the anchor tags so as to achieve an overlapping effect:

``` a.one {
z-index: 10;
-webkit-transform: rotate(-10deg);
-moz-transform: rotate(-10deg);
}
a.two {
z-index: 100;
-webkit-transform: rotate(-3deg);
-moz-transform: rotate(-3deg);
}
a.three {
z-index: 1000;
-webkit-transform: rotate(5deg);
-moz-transform: rotate(5deg);
}```

Now for the hover states …

First the anchor tag itself is given a hover state. Remember that Internet Explorer only allows :hover on anchor tags – this is why the anchor tag is needed! The z-index is changed to a high value, and the skew is corrected using transform: rotate(0deg). Absolute positioning is used: you can experiment with different values until you find the correct ones for your layout. Remember that absolute positioning positions elements relative to their nearest relatively positioned parent: in this case, the list item*. They are then given negative left and top margins to draw them back over the centre line.

*the list item has relative positioning added on the hover state below: don’t panic if positioning does not work correctly at this stage, you can return to it later.

```a:hover {
background-color: gray;
z-index:10000;
position: absolute;
width: 400px; height: 400px;
top: 50%; left: 50%;
margin-top: -200px; margin-left: -200px;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);```

Now change the images on the hover state, using the ids of the anchor tags:

```#first:hover {
background-image: url(birds400.jpg);
background-repeat: no-repeat;
background-position: 50px 0px;
}
#second:hover {
background-image: url('dragons400.jpg');
background-repeat: no-repeat;
background-position: 50px 0px;
}
#third:hover {
background-image: url('eels400.jpg');
background-repeat: no-repeat;
background-position: 50px 0px;
}```

### Fixing the Flicker

You will notice at this stage that the image has a tendency to flicker back and forward between different states. This is because the mouse pointer is hovering over different list items/anchor tags. To fix this, we add a very high z-index to the list item on :hover. This forces it to the front, where it takes up the whole space of the image. Notice that it is at this stage that the relative positioning was added to the list item in my example.

```li:hover {
position: relative;
z-index: 100000;
}```

Providing you have followed these instructions carefully, you should now have a fully-functional, attractive, CSS-based image gallery. A working example is viewable via the link below. Use view source in your browser to view the source code.

zoom

## HTML and CSS From Scratch. 10:1 Design Principals

August 25th, 2011

So now you know how to create a web site using HTML and CSS, but how do you make it beautiful and useful? This is an important aspect of web design. In other posts I have described how bad design causes stress and makes users more likely to leave your website, and the colour associations that may be used to underline the purpose of your website. In this article, I will cover some of the principals of beauty: the golden ratio, symmetry, a balance between complexity and simplicity, and colour schemes.

### The golden ratio.

Geometry has two great treasures:
one the Theorem of Pythagoras;
the other, the division of a line into extreme and mean ratio.
The first we may compare to a measure of gold;
the second we may name a precious jewel.
–Johann Kepler (1571-1630)

The division of a line which Johann Kepler was describing is often known as the golden ratio or golden mean. It is formally defined as a division whereby the sum of the two parts is in the same ratio to the larger of the two parts as the larger part is to the smaller one, and is an irrational number (a number which cannot be expressed accurately as a fraction). The golden ratio is roughly equal to 1.618. This number has been used to construct “beautiful” rooms, books and other works.

The golden ratio: where a is 1, b is 0.618 ....

So how can we use this ratio in web design? Well, a very simple way of approximating the golden ratio is to divide your page into nine equal boxes (see below). Then make sure that points of interest are placed on the left- or right-most dividing lines. Why? Because the golden ratio is roughly equivalent to two thirds of the web page, either from the left, or from the right. But there’s one more principal to be aware of: this brings us to the next section.

### Eye tracking.

Humans tend to look at pages or pictures in the same way that they are used to reading a page of text. For western English-speakers, this means that they tend to look at the top left corner first, and then their eyes zigzag down the page until they end up in the bottom right. Therefore, it’s best to put the company logo, tagline, or other important information, in the top left corner (roughly on the intersection described above). The corresponding bottom right corner is sometimes known as the corner of death, as this is the place where people are least likely to bother reading information. Never put anything really important in the corner of death!

Use nine boxes to find points roughly corresponding to the golden ratio.

Another good reason for putting the logo in the top left is simply that this has become a convention on the web: people expect to see it there. They also expect to be able to click on the logo and return to the home page.

As most people are right-handed, it has also become accepted convention to place vertical navigation links on the right-hand side. This is because it is easier to access them with the mouse when they are in that area: the rightmost column in your nine-box grid. However, another popular choice is the leftmost column, which also looks good.

### Aesthetics.

Two general principals to be aware of in terms of aesthetics (beauty) are those of symmetry and of an optimum balance between simplicity and complexity in your design. We tend to find symmetrical things more appealing: faces, butterflies and architecture all tend to be most beautiful when symmetrical. However, a little deviation from perfect symmetry can make the composition more interesting, as it adds an element of complexity and unexpectedness to the design. This brings us to the principal of a balance between simplicity and complexity: perfectly symmetrical designs are predictable and boring. Your design may need a little of the unexpected, or some more detail, to spice it up. However, no area should be so complex that it draws attention to itself. This is a sign that an area needs to be simplified or toned down, to allow it to blend into the overall design. One exception would be if the attention drawn enhances useability: for example an action button should perhaps be clearly visible. However, this should not be at the expense of attention paid to the rest of the page. Have someone else look at your page and ask them what they think: they will soon tell you if one area screams for attention.

Symmetrical shapes are more appealing.

### Colour Schemes.

A colour wheel can be a useful tool when picking colour schemes. Be aware of the associations that people have with different colours, and try to make sure that the dominant colour(s) of your website reflect its purpose and intended audience. Once you have decided on a general colour, it’s time to look at the colour wheel and pick out some extra colours to complete your design.

The most basic colour scheme uses harmonious shades to create a soft and subtle look. Pick three or more adjacent colours on the colour wheel, or for a tasteful and natural look pick shades from a photograph. This will give an even more gentle gradation of colours. Harmonious colour schemes are easy on the eye, relaxing and sophisticated.

The next most basic colour scheme is using complimentary colours for dramatic effect. Pick two colours opposite one another on the colour wheel. One should be your main colour, and the second can be used to add drama. Complimentary colour schemes can be very bold and dazzling: use with caution.

Triadic and quad colour schemes use three and four colours respectively, chosen from points equidistant around the colour wheel. You can combine these with harmonies of one colour, using the other two or three colours for accents.

Bright colours can also be used sparingly against a backdrop of neutrals for a dramatic modern look. Navy blue also makes a good neutral, as colours look very vivid against it. Chocolate brown and grey are also very modern-looking neutrals to use with an accent colour.

color wheel

When it comes to colour, experiment as you wish but be aware that people will spend less time on a website where the colours are not appealing!

## HTML5 For Web Designers by Jeremy Keith

August 23rd, 2011

Html5 For Web Designers

This tiny book almost makes you want to scream “it’s not a book, it’s a pamphlet” – and thank goodness for that! Sick and tired of long boring tomes full of waffle that you need a PhD in geekery to understand? Then HTML5 For Web Designers was written with you in mind, and not a moment too soon. HTML5 is here to stay, and we all need to get to grips with the fundamentals.

Everything that a web designer really needs to know about HTML5 is easily explained in this handy little reference book. Clear and concise, it is a quick read, and the well-organised and small sections mean it will be dipped into again and again whenever something needs to be looked up in a hurry.

Beginning with a brief history of HTML, the book quickly moves on to give the clearest and simplest explanation of HTML5 audio and video that I have yet seen. This is followed by explanations of the new semantic markup elements in HTML5, and canvas. The section on canvas seems to provide the missing jigsaw puzzle piece for those of us who are unfamiliar with the arcane art of DOM scripting, and once again the book achieves its aim of making a new skill seem attainable and even simple. The book also covers the new HTML5 form elements (and attributes), and rounds all of this off with a few alternative methods of incorporating HTML5 into web pages with current browsers.

As this book has been written with designers in mind it does lack some of the new features of HTML5: web workers, the geolocation API and databases are all missing. However, don’t let this put you off. This invaluable little book is a must-have and must-read for all web designers.

HTML5 For Web Designers by Jeremy Keith is \$18 from A Book Apart, ebook \$9.

## HTML From Scratch. 9:2 Special Characters.

August 17th, 2011

HTML Character Encodings

HTML allows the use of characters Aa-Zz and 0-9, together with ! and ?. The only quotes available for use in text are straight quotes. All other characters are known as ‘Special Characters’. So how do you include Special Characters? HTML Character Encodings.

All HTML Character Encodings begin with an ampersand (&) and finish with a semi-colon (;). Two alternative notations are available – one uses letters and is based on the names of the characters, the other uses only a hash symbol (#) followed by numbers. These are equivalent, and there is an alpha and a numeric alternative for each Special Character. Full tables of the character encodings can be found at http://www.w3schools.com/tags/ref_entities.asp.

### Why

The character encoding used for most HTML pages is ISO-8859-1, and the first 128 characters of that are those which appear by default in web pages (aA-zZ, 0-9, and a few others). These are the original ASCII character set. However, many of the remaining possible characters are reserved for use in programming (<>\$%&, etc) or other use, or they cannot be easily expressed with the keyboard (♥).

### The five essentials

HTML parsers are only required to recognise five special character encodings. As a matter of fact, Internet Explorer fails on one of these anyway.

&gt; < greater than

&lt; < less than

&amp; & ampersand

&quot; ” quote marks

&apos; ‘ apostrophe – does not work in IE.

Use other special characters at your peril: it is essential to test in all browsers and on a variety of machines to ensure that special characters used do indeed render.

### How

Simply type the Character Encoding in to the source code of your HTML at the point in your text where you need a special character. One key use is to produce code examples on a website: use &lt; and &gt; instead of < and >. When placing code on a website it can also be useful to use the HTML tags <code> and <pre>. The <code> tag simply allows its content to be separately styled with CSS, and is a semantic use of HTML. The <pre> tag produces pre-formatted text: all line breaks and spaces are preserved, and the text is rendered in a fixed width (typewriter) font by default.

### The non-breaking space

One extra special character which is invaluable to web designers is the non-breaking space (&nbsp;). This inserts a space character wherever it is used. Although it is often used to solve positioning problems in layouts, its semantic use is to prevent line breaks occurring within company names (or other proper names) which consist of multiple words:

Boy Scouts of America

Boy&nbsp;Scouts&nbsp;of&nbsp;America

## HTML From Scratch. 9:1 Forms

August 13th, 2011

Forms allow users to interact with your website.

It can be very useful to have a form on your website. Forms allow users to send feedback, contact information for newsletters, or buy products. Some forms allow users to upload content to the website: for example, an avatar on a social networking website. Most web forms are processed by scripts on the server written in a language such as PHP or Perl. Server-side scripts which process forms are known as CGI (Common Gateway Interface) Scripts, and if you want to you can learn how to write your own. For now, you will learn how to create a web form which is submitted by email. This only requires HTML, but you can use CSS to style your form.

### Form

The <form> tag is the foundation of your web form. This wraps around all of the content of your form, including all the buttons, boxes, selection fields and any labels or text. Its closing tag is </form>. The <form> tag takes various attributes, the most important of which are method and action.

Method takes two possible values: post and get. These refer to the method by which form data is returned to the processing script. Get passes all of the data as a single string, and is limited in size to 256 characters (more on some systems). The data is also passed in the url of the web page: making get a poor choice for any applications where security is a consideration. The data can be bookmarked or accessed through browser history, and manually altered by the user. The limited size is also another problem. Post passes data as a set of strings, each containing the information from one form field. It is also not visible to the user, and has no limit on the size of the data. This makes method=”post” the best choice in most situations.

Action usually takes as its value the url of the CGI Script which will process the form data, but for your email form you need the special command mailto: followed by your email address. This means that when the submit button is pressed, the user’s email program will open, with a pre-written email addressed to the email provided. Use enctype=”text/plain” for passing values UNCHECKED directly into an email program, and enctype=”multipart/form-data” for passing data to a CGI script using post.

Example:

<form method=”POST” action=”mailto:me@example.com” enctype=”text/plain”> …. </form>

### Input

The <input> tag nests inside the form tag, and represents a form field. Input takes many attributes, but the most important one is type. Type can take many values:

• text: text box.
• radio: radio button. This is a round button. Radio buttons are mutually exclusive: users can only select one option.
• checkbox: square box. These allow multiple selections.
• password: similar to text, but the entry is rendered with asterisks for security.
• hidden: takes a fixed value, and the form field is not shown.
• image: an active map, where the value submitted will be the x and y coordinates of the click.
• submit: submit the form.
• reset: clear the form fields.

Other attributes that input can take, and their values, include:

• name: a name given to the input field which is passed to the server-side script together with the value of the form field.
• size: number of characters in a text box before scrolling.
• maxlength: maximum number of characters in a text box.
• value: the value of this will give a default value for the form field, or the label of a button (e.g. submit).
• src: the url of the image used for an image form field.
• align: used with src to give alignment with text. Values taken are top, middle or bottom.

Example:
<input type=”image” name=”map” src=”map.jpg” align=”top”>
<input type=”text” name=”my_name” value=”Fred” size=”10″ maxlength=”15″>
<input type=”submit” name=”submit” value=”go!”>

### Textarea

The textarea tag is used inside a form to give a square box which can be filled with multiple lines of text. Its attributes and the values they take are:

• name: name for the server-side script
• rows: number of rows in the textarea
• cols: number of cols in the textarea

Example:

### Select and Option

The select tag gives a pulldown menu, whose items are given by the option tags nested inside. Select takes the attributes:

• name: name for server-side processing
• size: number of option elements displayed at once by pulldown without scrolling.

Example:
<option value=”1″>Burger</option>
<option value=”2″>Hot Dog</option>
<option value=”3″>Chips</option>
</select>

### Submit

The form is submitted by clicking on the submit button, or by clicking on an active map (which immediately returns data for processing), or or by pressing enter on the text box of a textarea.

### Extra Tags

There are a few extra tags which are not required but add to the semantic nature of your markup and aid accessibility.

• The label tag is used with an input element. It adds a text label, that selects the matching button or box with a mouse click. The for attribute should be equivalent to the id attribute given to the input element.

Example:
<label for=”myColor”>blue</label>

• The fieldset tag groups together elements in a form, and draws a neat box around them.

Example:
<fieldset>
<input type=”text”> …

</fieldset>

Example

live example

HTML5 has added many new input types to the specification. Some of these may not yet be fully implemented in all browsers, but you can experiment with them as you please:
W3.org html5 markup: input

## CSS From Scratch. 8:3 Fancy Boxes

August 10th, 2011

How do web designers manage to get those cool effects, like overlapping boxes, shadows and rounded corners? Well, it used to be fairly tricky to do, using extra <span> elements with background images (for rounded corners) and extra divs with darker backgrounds (for box shadows). Don’t even mention drop shadows on text: the only browser which attempted this was Internet Explorer, but it used proprietory filters which were unsatisfactory at best. Drop shadows are now possible using text-shadow, but we will not cover those in this lesson. We will, however, look at rounded corners, box shadows and the z-index (which allows boxes to overlap – this was a feature in CSS2.1 and has been mentioned in an earlier lesson).

### Z-index

We have already covered positioning elements with reference to x- and y-coordinates. Now we look at the third axis, z. This describes the depth of a point in 3-dimensional space. By default all elements have a z-index of 1. Elements with the same z-index cannot overlap. Overlapping is achieved by first assigning a different value of z, and then using positioning. Higher numbers represent an element that is ‘closer’, i.e. higher up in the stacking order. Lower numbers represent elements that are behind, or lower than others in the stacking order. The value of z can be any whole number, including negatives and zero.

div.special {z-index: -3;}

z-index gives the 3-d stacking order of elements

To add a shadow to an element, use the property box-shadow. This takes several values in a long list. These specify, in order, the x-offset (positive or negative integer, usually in pixels), the y-offset (same units), the amount of blur (pixels), the amount of spread (pixels), the colour of the shadow, and a last optional value which is inset. This last value inverts the shadow and places it inside the border of the box (see below).

Examples:

div.special {box-shadow: 2px 2px 5px 3px blue inset;}

div.other {box-shadow: 2px 2px 0 0 #cccccc;}

Multiple box shadows may be set on the same element, simply by listing a number of different sets of values separated by commas.

Example:

div.special {
box-shadow: 0 0 10px 5px black, 40px -30px lime, 40px 30px 50px red, -40px 30px yellow, -40px -30px 50px blue;
}

### Rounded Corners

Rounded corners can be given to an element using the border-radius property. Imagine a circle drawn so that its edge is just touching two sides of the box, and then cutting around a quarter of the circle to create a rounded edge. The radius of a circle is the distance between its centre and its outer edge: this value gives the amount of curvature on the box.

The radius is the distance from the centre to the outer edge.

The four corners of the box can be separately given, so all four corners can have different curves or none at all. This is done using the following notation:

div.special {

}

A border-radius of 0 gives a right angle.

Border-radius can take two values instead of just one. When two values are given, these specify the horizontal radius and vertical radius in order. So the curve becomes a section of an elipse rather than a circle.

Example:

Eliptic corners from the W3C website.

### Vendor-specific prefixes

For many CSS3 properties there is specific syntax that needs to be used to get a particular browser to obey the rule. These use vendor (browser) specific prefixes, and the syntax for both the property and the value may vary from the official syntax. You will need to look these up unless you are using a particular property very often, as they are sometimes very different from the official version. Simply list all of the alternatives in your CSS: other browsers will ignore properties using the prefix for another browser. When you have to include these special versions of CSS3 properties and values, always make sure the last one in the list is the generic version. This is because as browsers become more up-to-date they may begin to read the correct syntax, and the last rule in the list will always override earlier rules.

The prefixes are:

-moz- [mozilla: this targets FireFox]

-webkit- [webkit: this targets Safari and Chrome]

-o- [opera: this targets Opera]

-ie- [trident: this targets Internet Explorer]

### More CSS3 properties

There are many more CSS3 properties which can be used on boxes to alter their appearance or behaviour. Some of the most exciting include translate, transform and gradient. You can find information on all of these and more at:

css3files.com

css3.info

## CSS From Scratch. 8:2 Background images.

August 10th, 2011

Many experts agree that it is best to include images in your web page using CSS. This makes it easier to edit them later, and maintains the separation of concerns (CSS used only for appearance, HTML used only for semantic markup). Others disagree, and say that it is better for accessibility to use HTML <img> tags with the alt attribute, as screen readers can recognise the <img> tag and will read aloud the value of alt. It’s up to you to decide which is more appropriate for each picture on your website: decorative features may be best in CSS, where they will be invisible to screen readers; photos of your latest holiday may be best in HTML, so that blind or partially-sighted visitors can hear a description.

You can add a background with CSS to any element with the property display:block (this includes block-level elements, which have this property by default), as long as it also has width and height. You may notice that when a span is given display:block, it still has no height until this is assigned: span is the commonest element used to display graphics, so bear this in mind.

The basic property used to give a background to an element is background, but before looking at the shorthand which allows you to list all values in one declaration here are all properties (and their values) listed separately:

• background-color: [hex or decimal colour value or colour name];

This sets the background colour of the element. Remember that it is also possible to set transparency using rgba or hsva.

• background-image: url(‘somePic.jpg’);

This sets a background image. By default the image is placed in the top left corner of the element, and then will be repeated until it covers the whole of the element.

• background-repeat: [repeat-x or repeat-y or no-repeat];

To control the direction of the repeated background image use repeat-x (repeat the image only in a horizontal direction) or repeat-y (repeat the image only in a vertical direction). This can give a stripe across the top or down the side of an element. To prevent the image from repeating at all use no-repeat. This value is often given even though an image fits the element exactly, just to make doubly sure that there are no inconsistencies.

• background-attachment: [scroll or fixed or inherit];

This is similar to using position:fixed, but for a background image. The default is scroll (the image scrolls with the page). Fixed will mean that the image remains in place while the rest of the page scrolls. Inherit always means that the property takes the same value of that given for the parent element.

• background-position: [top left or bottom right or top right or bottom left or percentages or units];

This enables you to set the starting position of the background image. The default is top left (the top left corner). You can use the key words top left bottom and right, or set the position using percentages for x and y coordinates or units such as px, em and pt. Remember that when a computer draws an image on a screen it begins from the top left corner, and then “writes” lines across, working line by line down the screen. This means that y-coordinates are calculated from the top of the box by default, in contrast to most mathematical diagrams where y-coordinates are calculated from the bottom upwards!

The shorthand property background simply takes as values the values of the properties listed above. They are listed in the same order given above, but many are optional. Only a background-color or background-image is essential – or there will be no content for the other properties to apply to!

Example:

background: #ff0000 url(‘myPic.gif’) no-repeat fixed top right;

background: url(‘myNewPic.jpg’) repeat-x left 50%;

## CSS From Scratch. 8:1 Pseudoclasses

August 10th, 2011

pseudoclasses allow extra behaviours

The commonest use of pseudoclasses is to add styles for different states of an anchor (link) element. This includes the hover state – when the mouse hovers over an element, the style changes. Internet Explorer only recognises hover on an anchor tag, but other browsers may allow hover states on any other elements.

The basic syntax of a pseudoclass is:

element:pseudoclass {property: value}

Example:

a:hover {color: red;}

The pseudoclasses that may be used on anchor tags reflect the different possible states of that tag – the default behaviour of the browser is to use different colours for links, visited links and active links. Pseudoclasses also add the possibility of changing styles when the mouse hovers over the link (mouseover in javascript) and on keyboard focus for those using tabbed navigation.

a:visited

a:hover

a:active

a:focus

Although the focus pseudoclass is optional, it is important to remember that when using the above pseudoclasses the first four must always be listed, even if they are left unstyled. They must also be listed in the above order, which can be remembered using the mnemonic LoVe HAte (link, viewed, hover, active). Focus may also be used to style form elements, which can be tabbed through by those using keyboard navigation or assistive devices. This makes it a useful addition for acessability.

There are many other pseudoclasses, and more have been added in CSS3; however, browser support for pseudoclasses is still not complete.  Be careful when using these new selectors.

Older and more reliable pseudoclasses from CSS2.1 include:

• :first-letter

Selects the first letter in a block of text for styling.

• :first-line

Selects the first line in a block of text for styling.

• :before and :after

Use with the property content to add content either before or after the named element.

Example: p:before {content: url(‘smiley.gif’);}

• :lang(…)

Selects a portion of text which has been given the html lang attribute. The value of lang should be included inside the brackets. Lang specifies the language of text on a web page, and using this pseudoclass enables different languages to be styled in different ways.

#### CSS3 Pseudoclasses

The full list of pseudoclasses added in CSS3 can be found here:

Sitepoint CSS3 Pseudoclasses

Remember to use these with caution. Keep newer pseudoclasses to inessential styling if possible, to avoid issues with readability of your page. Internet explorer in particular does not recognise the nth-child pseudoclass.

## HTML From Scratch. 7:3 Meta tags

August 7th, 2011

Use "keywords" for Search Engine Optimisation

We already used a meta tag in the head of our html code:

<meta charset=”UTF-8″>

Meta tags add extra information in the head of the html, for use by the browser or by web crawlers. The attribute name can take any value, so the following are all valid:

<meta name=”author” content=”Fred Bloggs”>
<meta name=”favourites” content=”chocolate, purple, cats”>
<meta name=”keywords” content=”cats, animals, pets”>

The most commonly used value is keywords. This is used for Search Engine Optimisation (SEO), although many experts consider it outdated and recommend the use of semantic code and keywords in the text of your page instead. Web crawlers such as Googlebot can read the keywords and gain knowledge about the content of your website. Separate keywords (or phrases) with commas.

Another popular value is description, which will give the line of content displayed by Google on its search results page under the title of your page.

<meta name=”description” content=”My page about my pet cats.”>

gives:

My Cats Dot Com
My page about my pet cats.

Another interesting attribute which meta tags can take is http-equiv. This can take many values, but perhaps the most useful is refresh. The value of content will give the number of seconds before the page will automatically refresh, with the option of adding an url after a semi-colon in order to reload a different page.

<meta http-equiv=”refresh” content=”60″; url=”myNewPage.html”>

The attribute redirect can also be used with refresh in order to secretly redirect the page.

<meta http-equiv=”refresh” content=”60″; redirect=”secret.html”>

These can be combined together in creative ways, as long as logic is obeyed, in order to produce effects such as slideshows, automatic logouts, and to cue users to update their bookmarks when a site’s web address has changed.

Key point: use keywords and descriptions for SEO.