Category: CSS

Advanced CSS: Adjacent Sibling Selectors

In my web articles thus far, when I’ve talked about CSS it’s been in terms of the basics: the box model,relative positioningpage flow, etc. In the Advanced CSS articles, I’ll be talking about aspects the you wouldn’t normally find on every page. This isn’t necessarily new stuff from CSS3, just things that you wouldn’t normally need to know to do CSS design, but can come in handy sometimes.

Generally with CSS, we select an element based on its class or ID and on its ancestors. However, sometimes we need to be a little more specific. For example, suppose that every paragraph in each section, starting with the third paragraph, should have special formatting. (Why that might be, I don’t know…but CSS is very flexible!) The adjacent sibling selector will let us do this! We simply write:

p + p + p {

rules go here

}

This says that the style only applies to paragraphs which have two preceding siblings, where a sibling is another child of the same parent.

This example was a little contrived; how about another one? Suppose that we have a page with a number of h2 and h3 headers, and we want the first h3 header in each section to have special formatting. We can’t use the :first-child psuedo-class because the h3 we want is not actually a child of any h2; it simply appears immediately after it. As such, we’ll use the following code:

h2 + h3 {

font-color: #6CFF0A;

}

Now every h3 tag which immediately follows an h2 tag is bright green, as desired.

Note: the adjacent sibling selector does not work…wait for it…in IE6 and below.

Cross-Browser Compatibility

One thing that causes a lot of headaches for web developers is getting sites to look good in every browser.

Notice that I did not say, getting a site to look the same in every browser. While it’s possible to get a site to look more or less the same, there are always going to be minor differences and it’s generally more trouble than it’s worth. As long as the site looks good and has consistent branding, there’s no reason that it needs to look identical on every computer.

Once you realize that, web design becomes much less of a hassle. One method is to build out a basic site that will work in every browser, then add flourishes that will improve the viewing experience for people with modern browsers, without taking anything away from those who are still using older browsers.

HTML5 and CSS3 offer some great examples.  Suppose you want to have some really nice-looking buttons. You can put in rounded corners and add a background gradient to make the buttons stand out.  Visitors running Internet Explorer won’t be able to see this, and will just get the regular old buttons, so to them it’s the same as if you didn’t make any changes at all, but other visitors get an enhanced browsing experience.

Or consider HTML forms. The new input types in HTML5 degrade gracefully; any browser that doesn’t know how to handle them simply treats them as text inputs instead. As a result, older browsers get the same experience they always have, but more modern browsers get a better presentation.

In short: design your sites to look good on every major browser. Then, if you like, use modern tools such as HTML5 and CSS3 so that, on modern browsers, the sites look even better.

Page Flow, Inline and Block Elements, and Relative Positioning

The HTML flow model is pretty simple: every element goes in a box, and the web browser stacks up those boxes when you view the page. Block boxes, which are generated by tags such as <p> and <h1>, get stacked on top of each other, while inline elements stay (surprise, surprise) in a line (unless the line reaches the edge of the container, in which case it runs over to the next line). Easy enough, right? Although elements have a default type (block or inline), you can change this in your CSS with the display: property. You can also set display: none, which keeps the element from being displayed on the page at all. All of these elements, whether block or inline, are considered to have static positioning.

However, when you use relative positioning, this actually removes an element from the flow. Your browser will render the page as if the relatively positioned element is where it’s “supposed” to be, but you can actually move it around; this may result in it covering up other elements. Absolutely positioned elements are also removed from the flow; as previously discussed, they’re placed relative to the closest ancestor which is relatively positioned (this may be the html element). While other elements behave as if relatively positioned elements are still at their normal location, they act as if absolutely positioned elements do not exist. Every absolutely-positioned element has its own z-index level, so that it will appear above or below anything it overlaps with (even other absolutely positioned elements); while these are set by default (with elements that appear later in the file getting larger z-numbers and appearing on top), you can override them using the z-index property.

Tip: Ever end up with an unclickable link on your webpage? This may be caused by a transparent, absolutely positioned element which is covering up the link. IE7 and below have a bug that allows you to click through the above element, so you’ll actually see the behavior you want (a clickable link) in IE6 and IE7, but not in modern browsers.

Understanding Relative Positioning in CSS

One aspect of CSS that can be a bit confusing (not that there aren’t plenty of those) is relative vs absolute positioning. It really seems a bit backwards at first.

Suppose you have the following code:

#container {
position: relative;
}

You might think this means that you’re not positioning container relative to something else, but in fact it means that other boxes inside container can be positioned relative to it. If you give absolute positioning to elements inside container, they’ll now have an absolute position relative to the container. Confusing enough? Consider this example:

#badlynamedbox {
position: absolute;
top: 0;
left: 0;
}

Badlynamedbox will now appear in the upper left corner of the container, not the brower window (although it’s possible these could be the same). Very useful! More formally, an absolutely positioned element will be positioned relative to the first relatively positioned ancestor; if there are no ancestors that are explicitly defined to be relatively positioned, this will be the html element.

CSS Programming and IE6, Part 2: The Box Model

Let’s start with a quick review of the CSS box model.

Suppose I have a div. From the outside in, I first have the margin, which is distance from the surrounding elements. Then there’s a border. Inside the border is padding, and inside that is the content.

In a modern browser, the total width that the div takes up on the screen (from the border in) will be the combined widths of the content, padding, and border. For example, given a div with width of 80px, border 3px, padding 7px will take up 100 pixels (80 + 3 + 3 + 7 + 7), as specified by the CSS standard. In IE6, it will take up 80 pixels, as internet explorer considers the border and padding to be part of the specified width. Accordingly, if you use the same style sheet for all browsers, your divs are likely to look much thinner when viewed with IE6.

The other major problem related to the box model is known as the double margin bug; when a box is floated against the edge of the containing div, IE6 will double the margin on that edge.  There are several hacks to fix this; without getting into why they work, just know that you can get rid of the error by adding one of two statements:

display: inline;
zoom: 1;

Neither should have any effect on other browsers; in fact, because zoom is a Microsoft-specific thing (nothing other than IE recognizes it), non-Microsoft browsers will ignore it completely (although it will make your style sheet fail a CSS standards check).

CSS Programming and IE6, Part 1: Checking Compatibility

Like nearly all web designers, I detest making sites work in IE6. The browser is ancient; it released in 2001! There is absolutely no reason for anybody to still be using it.

Unfortunately, for some reason, people still do. This means we have to make our websites accessible to IE6 or lose a  fairly sizable minority of our users. With plain HTML, this generally isn’t a big issue, but IE6 understandably has somewhat limited CSS support (it is, after all, over nine years old!) This naturally leads to websites that are essentially unreadable to users who’ve never upgraded. In the near future, as computers running Windows XP (which shipped with IE6) reach the end of their lives, it should become irrelevant, but for now there are a few things you can watch for to keep your sites accessible.

First off, of course, is to check how the site currently looks. Chances are, you don’t have IE6 installed on your computer, but there are sites that will show you how it looks; I use netrenderer. It won’t look the same as it does in other browsers, but if it reads reasonably well, you probably want to just call it good.

But suppose it’s totally screwed up. In that case, you probably want to import an IE6-specific stylesheet that fixes the major issues; you can do so using the following code. (Remember to put this after your other style sheets are imported so that it overrides them).

<!--[if IE 6]>
	<link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->

If you want to target every version of IE from six on down, you can instead use [if lte IE 6]. Throwing in an if statement like this allows you to serve up a simple stripped-down stylesheet that early browsers can understand, while keeping the extra code out of the main style sheet that everyone else will download.

Creating Equal (Fixed Width) Columns With CSS

Suppose you’re designing a webpage where content is in multiple columns, each of thich has a different background. It looks pretty stupid if the columns end in different places, doesn’t it? If you program WordPress themes or similar, it can look REALLY bad. So how can you make sure the columns line up?

If each column has a fixed width, it’s actually pretty easy.  Put all of the columns inside a fixed-width container, and set the background for that container to be a repeat-y image that has the appropriate background color for each part of the row. This technique was popularized by Dan Cederholm in 2004, in his article on Faux Columns.

When the columns have variable widths, it’s a bit more difficult. But that’s an issue for another post.

The CSS !important Specifier

One of the challenges people new to Cascading Style Sheets face is figuring out why the rule they just coded doesn’t seem to be doing anything. Once you start building more complex websites, it’s likely that several rules will apply to a single HTML tag. In some cases, all of the styles can be applied; for example, you could say that everything in your content area will be colored green, then say that your paragraphs will have size 12 font, and you’ll end up with green, size 12 text. But what happens when styles contradict?

As it happens, you can (mostly) figure out which style will take precedence by doing a little math. If you’ve used an inline style applied directly to the element in question, it has weight 1000 (and almost certainly wins). Otherwise, add up 100 for each ID in the style, 10 for each class, and 1 for each element. Psuedo-classes (such as :hover) cound the same as real classes, as do attribute selectors (such as [type=”submit”]) Psuedo-elements (such as :first-letter count the same as real elements. Highest number wins!

In case of a tie, whichever specifier is encountered last is considered to be more important. This applies to both internal and external styles, so if you import several external style sheets, whichever one is important last will win all ties.

So what do you do if your new style doesn’t seem to be working? Well, from a practical standpoint, the first thing to do is make sure you haven’t mistyped anything, maybe mistyped a class name or used a . where you need a #. After that, the best thing to do is to make your selector more specific – that is, add more IDs and classes to give it greater weight –  so that it will override the less specific selectors.

However, if you have a style that absolutely MUST apply in all situations, you can use the !important selector.  (Does anybody else read that as saying “not important”?) This selector applies only to one particular property, not the entire block. For example, suppose I have this code:

#container {
color: black !important;
font-family: ‘Cambria’, ‘Times New Roman’;
}

#content {
color: red;
font-family:Arial, Helvetica, sans-serif;
}

Any text that is inside the content box, which is inside the container, will be in Arial…but it will be black.

The !important statement should be used only sparingly; not only do you not want two !important statements to ever apply to the same line of code, but it’s a real pain to have your selector not working because there’s an !important line somewhere in your external style sheets!

Cascading Style Sheets

In the past, I haven’t done a lot of CSS work; my interests lie more in the areas of SEO and content. We needed a WordPress programmer, though, and before I could start programming WordPress themes, I needed to brush up on my CSS and PHP. Fortunately, I had a decent book sitting around: O’Reilly’s CSS: The Missing Manual. After a few hours reading the book and playing with the CSS in some WordPress themes, it all makes sense; my only hesitation in recommending the book comes from the fact that, because it was released last year, it contains less than a hundred pages on CSS3.

I’ve probably mentioned this before, but if you’re not familiar with what Cascading Style Sheets can do, you need to run, not walk, over to the css Zen Garden and play with it a bit. Good programming practice for the web these days, and what HTML5 is built on, is the separation of style from content. HTML5 holds the content; CSS should be used to indicate to the browser how to display it. What’s really nice about this is that by using an external style sheet for your website, if you decide to change the look and feel of the site you can immediately alter every page (drastically, if desired) simply by editing one file.

CSS is really pretty simple. Suppose that I wanted to change how the text in each of these  posts is displayed. Let’s say that, for some reason, I wanted the text to appear in bright orange. In WordPress, the posts are contained in the following tags: <div id=”content”></div>. Thus, I would simply add the following code to my style.css file:

#content {
color: #FF7F00;
background: #FFFFFF url(‘images/background.jpg’) no-repeat;
}

So what does all that mean? The hash mark before the name of the div means that this is an ID, which is something that should appear at most once on each page; something that can appear multiple times should be a class and is indicated using a period. Everything between the brackets is CSS code that will apply to the contents of the content div; in this case, #content is called a selector because it selects this particular part of the HTML. Inside the brackets I can have any number of declarations; in this case I just have two. Each declaration is a property followed by a colon and then a value; some properties can take on multiple values. For example, here I told the browser that it should render the content area with a white background, use the file background.jpg in the images directory as a background image, and that that image should not repeat. If I later decide to use a less hideous color combination, all I have to do is edit this one file.

Aside from making my life a lot easier when I have to change something, this can also reduce the amount of space the code for a site takes up, as the formatting only has to be stored (and downloaded) once, rather than once for each page. This helps speed up the process of loading your site, which helps to keep Google and your customers happy.