Understand css Positioning element

Positioning is tough to understand when you’re first starting out with CSS. Your choices are

  1. Static
  2. Relative,
  3. Absolute,
  4. Fixed.

Static is the default option and is positioned according to the normal page flow.

Relative item is positioned relative to itself, meaning you can move it up, down, left or right, based on where it would normally sit.

Absolute allows you to place an item anywhere on the page, and is the most misused positioning statement. The values you set for it will be relative to the last parent item with relative or absolute, and if there aren’t any, it defaults back to the html tag, allowing you to position it anywhere by declaring top left right or bottom values.

Fixed is positioned relative to the browser window, so an item will stay in place if a user has to scroll. Learning how to use positioning correctly is important, but shouldn’t be used excessively. I rarely use these at all in my stylesheets.

Advertisements

The simplest way to horizontally and vertically center a DIV

I have gone trough a lot of ways to horizontally and vertically center a DIV. Many of the code snippets had a Child DIV1 inside a Parent DIV2 to center the Child. They work perfect but I found a simpler way to center a single DIV trough CSS.

I am not sure if this is already known to all, but I experimented and came up with this simple CSS snippet.

Here is a visual representation of how this works:

vertically center a div

Here is the CSS Snippet to be assigned to the DIV to be centered. The size of the DIV is 100 x 100 px ( same as the above example ).

/* CSS Document */

.centered_div {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background: red;
}

Here is another example with size 500 x 200 px.

/* CSS Document */

.centered_div {
width:500px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -100px;
background: red;
}

You can also find an online example here

Some usefull css tips, tricks

CSS font shorthand rule

When styling fonts with CSS you may be doing this:

font-size: 1em;
line-height: 1.5em;
font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-family: verdana,serif;

There’s no need though as you can use this CSS shorthand property:

font: 1em/1.5em bold italic small-caps verdana,serif

Much better! Just a couple of words of warning: This CSS shorthand version will only work if you’re specifying both the font-size and the font-family. Also, if you don’t specify the font-weight, font-style, or font-varient then these values will automatically default to a value of normal, so do bear this in mind too.

2. Two classes together

Usually attributes are assigned just one class, but this doesn’t mean that that’s all you’re allowed. In reality, you can assign as many classes as you like! For example:

<p class="text side">...</p>

Using these two classes together (separated by a space, not with a comma) means that the paragraph calls up the rules assigned to both text and side. If any rules overlap between the two classes then the class which is below the other in the CSS document will take precedence.

3. CSS border default value

When writing a border rule you’ll usually specify the colour, width and style (in any order). For example, border: 3px solid #000 will give you a black solid border, 3px thick. However the only required value here is the border style.

If you were to write just border: solid then the defaults for that border will be used. But what defaults? Well, the default width for a border is medium (equivalent to about 3 to 4px) and the default colour is that of the text colour within that border. If either of these are what you want for the border then you can leave them out of the CSS rule!

4. !important ignored by IE

Normally in CSS whichever rule is specified last takes precedence. However if you use !important after a command then this CSS command will take precedence regardless of what appears after it. This is true for all browsers except IE. An example of this would be:

margin-top: 3.5em !important; margin-top: 2em

So, the top margin will be set to 3.5em for all browsers except IE, which will have a top margin of 2em. This can sometimes come in useful, especially when using relative margins (such as in this example) as these can display slightly differently between IE and other browsers.

(Many of you may also be aware of the CSS child selector, the contents of which IE ignores.)

5. Image replacement technique

It’s always advisable to use regular HTML markup to display text, as opposed to an image. Doing so allows for a faster download speed and has accessibility benefits. However, if you’ve absolutely got your heart set on using a certain font and your site visitors are unlikely to have that font on their computers, then really you’ve got no choice but to use an image.

Say for example, you wanted the top heading of each page to be ‘Buy widgets’, as you’re a widget seller and you’d like to be found for this phrase in the search engines. You’re pretty set on it being an obscure font so you need to use an image:

<h1><img src="widget-image.gif" alt="Buy widgets" /></h1>

This is OK but there’s strong evidence to suggest that search engines don’t assign as much importance to alt text as they do real text (because so many webmasters use the alt text to cram in keywords). So, an alternative would be:

<h1><span>Buy widgets</span></h1>

Now, this obviously won’t use your obscure font. To fix this problem place these commands in your CSS document:

h1
{
background: url(widget-image.gif) no-repeat;
}
h1 span
{
position: absolute;
left:-2000px;
}

The image, with your fancy font, will now display and the regular text will be safely out of the way, positioned 2000px to the left of the screen thanks to our CSS rule.

6. CSS box model hack alternative

The box model hack is used to fix a rendering problem in pre-IE 6 browsers, where by the border and padding are included in the width of an element, as opposed to added on. For example, when specifying the dimensions of a container you might use the following CSS rule:

#box
{
width: 100px;
border: 5px;
padding: 20px;
}

This CSS rule would be applied to:

<div id=&quot;box&quot;>...</div>

This means that the total width of the box is 150px (100px width + two 5px borders + two 20px paddings) in all browsers except pre-IE 6 versions. In these browsers the total width would be just 100px, with the padding and border widths being incorporated into this width. The box model hack can be used to fix this, but this can get really messy.

A simple alternative is to use this CSS:

#box
{
width: 150px;
}

#box div
{
border: 5px;
padding: 20px;
}

And the new HTML would be:

<div id=&quot;box&quot;><strong><div></strong>...<strong></div></strong></div>

Perfect! Now the box width will always be 150px, regardless of the browser!

7. Centre aligning a block element

Say you wanted to have a fixed width layout website, and the content floated in the middle of the screen. You can use the following CSS command:

#content
{
width: 700px;
margin: 0 auto;
}

You would then enclose <div id=&quot;content&quot;> around every item in the body of the HTML document and it’ll be given an automatic margin on both its left and right, ensuring that it’s always placed in the centre of the screen. Simple… well not quite – we’ve still got the pre-IE 6 versions to worry about, as these browsers won’t centre align the element with this CSS command. You’ll have to change the CSS rules:

body
{
<strong>text-align: center</strong>;
}

#content
{
<strong>text-align: left</strong>;
width: 700px;
margin: 0 auto;

}

This will then centre align the main content, but it’ll also centre align the text! To offset the second, probably undesired, effect we inserted text-align: left into the content div.

8. Vertically aligning with CSS

Vertically aligning with tables was a doddle. To make cell content line up in the middle of a cell you would use vertical-align: middle. This doesn’t really work with a CSS layout. Say you have a navigation menu item whose height is assigned 2em and you insert this vertical align command into the CSS rule. It basically won’t make a difference and the text will be pushed to the top of the box.

Hmmm… not the desired effect. The solution? Specify the line height to be the same as the height of the box itself in the CSS. In this instance, the box is 2em high, so we would insert line-height: 2em into the CSS rule and the text now floats in the middle of the box – perfect!

9. CSS positioning within a container

One of the best things about CSS is that you can position an object absolutely anywhere you want in the document. It’s also possible (and often desirable) to position objects within a container. It’s simple to do too. Simply assign the following CSS rule to the container:

#container
{
position: relative;
}

Now any element within this container will be positioned relative to it. Say you had this HTML structure:

<div id=&quot;container&quot;><div id=&quot;navigation&quot;>...</div></div>

To position the navigation exactly 30px from the left and 5px from the top of the container box, you could use these CSS commands:

#navigation
{
position: absolute;
left: 30px;
top: 5px;

}

Perfect! In this particular example, you could of course also use margin: 5px 0 0 30px, but there are some cases where it’s preferable to use positioning.

10. Background colour running to the screen bottom

One of the disadvantages of CSS is its inability to be controlled vertically, causing one particular problem which a table layout doesn’t suffer from. Say you have a column running down the left side of the page, which contains site navigation. The page has a white background, but you want this left column to have a blue background. Simple, you assign it the appropriate CSS rule:

#navigation
{
background: blue;
width: 150px;
}

Just one problem though: Because the navigation items don’t continue all the way to the bottom of the screen, neither does the background colour. The blue background colour is being cut off half way down the page, ruining your great design. What can you do!?

Unfortunately the only solution to this is to cheat, and assign the body a background image of exactly the same colour and width as the left column. You would use this CSS command:

body
{
background: url(blue-image.gif) 0 0 repeat-y;
}

This image that you place in the background should be exactly 150px wide and the same blue colour as the background of the left column. The disadvantage of using this method is that you can’t express the left column in terms of em, as if the user resizes text and the column expands, it’s background colour won’t.

At the time of writing though, this is the only solution to this particular problem so the left column will have to be expressed in px if you want it to have a different background colour to the rest of the page.

Link selector Specificity

While it’s always possible that you have a stupid browser– that’s not really for me to say– it is more often the case that the styles have simply been written in the wrong order. To ensure that you see your various link styles, you’re best off putting your styles in the order “link-visited-hover-active”, or “LVHA” for short. If you’re concerned about focus styles, they may go at the end– but wait until you’ve read this explanation before you decide.

The core of the situation is this: every selector has a specificity. If two selectors apply to the same element, the one with higher specificity wins. Thus:

 P.hithere {color: green;}    /* specificity = 1,1 */
 P {color: red;}              /* specificity = 1   */

So any paragraph which has a class of hithere will be green, not red. Both selectors apply, and both try to set the color, so the more-specific selector wins out.

Aside: this only comes into play when the same property is involved. Thus:

   P.hithere {color: green;}    /* specificity = 1,1 */
   P {font-family: Courier;}    /* specificity = 1   */

All paragraphs will be in Courier, but those with a class of hithere will be in Courier and green in color.

Okay, so how do pseudo-classes affect specificity? They all have equal weight, as it turns out. So the following styles all have the same specificity:

 A:link {color: blue;}        /* specificity = 1,1 */
 A:active {color: red;}       /* specificity = 1,1 */
 A:hover {color: magenta;}    /* specificity = 1,1 */
 A:visited {color: purple;}   /* specificity = 1,1 */

All of them can apply to a hyperlink, and in some cases, more than one will apply. For example, an unvisited link can be hovered and active at the same time as it’s an unvisited link. Since three of the above rules apply to the hyperlink, and the selectors all have the same specificity, then the last one listed wins. Therefore, the “active” style will never appear, because it will always be overridden by the “hover” style. Now consider a hyperlink which has been visited. It will always and forever be purple, because its “visited” style beats out any other state, including “active” and “hover.”

This is why the recommended order in CSS1 goes like this:

   A:link
   A:visited
   A:hover
   A:active

The first two can be in either order, actually, because a link can’t be both visited and unvisited at the same time. (:link means “unvisited”; and no, I don’t know why they didn’t call it that.)

This is also why CSS2 now allows the chaining of pseudo-classes. For example, you could write:

   A:visited:hover {color: maroon;} /* specificity = 2,1 */
   A:link:hover {color: magenta;}   /* specificity = 2,1 */
   A:hover:active {color: cyan;}    /* specificity = 2,1 */

They have the same specificity, but they apply to fundamentally different beasts, and so don’t conflict. You can get hover-active combinations, for example.

Finally, a word about how I represented specificity in this article. The specification simply concatenates numbers together, so that the first example in the post would have been written like this:

   P.hithere {color: green;}    /* specificity = 11 */
   P {color: red;}              /* specificity = 1  */

This implies a base-ten arithmetic. However, specificity calculations do NOT use base ten, a fact at which the specification hints but doesn’t come right out and say in big bold letters. If you chain fifteen simple selectors together, they still have a lower specificity than a simple class selector. Here’s how the specification would represent this:

   .hello {color: red;}    /* specificity = 10 */
    HTML BODY DIV UL LI OL LI UL LI OL LI UL LI OL LI {color: green;}
   /* specificity = 15 */

That “10” is actually a 1 followed by a zero, not “ten.” We could try representing the previous rules specificities in hexadecimal, like this:

   .hello {color: red;}    /* specificity = 10 */
   HTML BODY DIV UL LI OL LI UL LI OL LI UL LI OL LI {color: green;}
   /* specificity = F */

The only problem there is that if you try to add two more selectors to the second rule, then you get a specificity of 11, and once again we get confused. In fact, the counting base for specificity is effectively infinite, and so these kinds of comparison start to break down. So I’m switching over to comma-delimited specificity calculations in the future just to avoid more confusion.

CSS specificity

CSS: Specificity Wars

Join me, and together we can rule the galaxy as father and geeks!

A few weeks back in Cupertino, I saw Aaron explain how the specificity of CSS selectors is calculated in a way which I hadn’t seen before. Then today I came across a knotty problem while building XHTML and CSS templates for a new project where two selectors behaved differently to how I expected and I realised that I had not completed my training.

The Dark Side

My problem was a simple one, how to feed a transparent PNG image to browsers which support transparency and a GIF image to older browsers which don’t, without resorting to hacks. Here’s the markup,

<div id="nav-supp">
<p><a id="a-02" href="#webstandards-org">Top</a></p>
<!-- etc. -->
</div>

and my CSS starting point.

a#a-02 { background-image : url(n.gif); }
a[id="a-02"] { background-image : url(n.png); }

I had assumed that a modern browser would see and apply both rules (with the second overriding the first) and that an older browser which does not understand attribute selectors would see and apply only the first, ignoring the second. I was wrong. Modern browsers did not apply the PNG image as I expected. The reason? A standard id selector wins over an attribute selector in terms of the cascade. Dagnammit! I know I should have read the specs, but somehow that particular pleasure had escaped me. If I had, I might have learned that;

ID selectors have a higher specificity than attribute selectors. For example, in HTML, the selector #p123 is more specific than [id=p123] in terms of the cascade.

Sith Lords

A little Googling uncovered some rather dry reading on the subject of selector specificity (resources below).

First, let’s look back at what Lord Elasticus (Patrick Griffiths) wrote on the subject of specificity (with one or two minor changes to fit our nefarious purpose).

You give every id selector (“#whatever”) a value of 100, every class selector (“.whatever”) a value of 10 and every HTML selector (“whatever”) a value of 1. Then you add them all up and hey presto, you have the specificity value.

  • p has a specificity of 1 (1 HTML selector)
  • div p has a specificity of 2 (2 HTML selectors; 1+1)
  • .sith has a specificity of 10 (1 class selector)
  • div p.sith has a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)
  • #sith has a specificity of 100 (1 id selector)
  • body #darkside .sith p has a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

If all of these examples were used, div p.sith (with a specificity of 12) would win out over div p (with a specificity of 2) and body #darkside .sith p would win out over all of them, regardless of the order.

Darth (Gez) Lemon quotes the W3C.

A selector’s specificity is calculated as follows:

  • count the number of ID attributes in the selector (= a)
  • count the number of other attributes and pseudo-classes in the selector (= b)
  • count the number of element names in the selector (= c)
  • ignore pseudo-elements.

Concatenating the three numbers abc (in a number system with a large base) gives the specificity.

Too much! For me, the W3C really is in a galaxy far, far away!