men

CSS pseudo-element Solar System

This is a remix of another author’s idea of using CSS to make a classic model of our solar system. Here, I’ve relied on CSS pseudo-elements and generated content to render scale models of the solar system from simple markup of the raw information.

There are three demos for this experiment, which is based on Alex Giron’s original Our Solar System in CSS3.

The basic demo uses only CSS and simple, semantic HTML to relatively faithfully reproduce Alex’s original result.

The advanced demo is a rough scale model of the Solar System. It uses the same HTML as the “basic demo” but makes extensive use of CSS pseudo-elements, generated content, and various bits of CSS3.

The advanced demo (keyboard support) is an attempt to provide keyboard support by introducing slight modifications to the HTML. I’ve commented out the animations in this version of the demo.

Why rework the original experiment?

I was curious to see if the same result could be achieved with simpler HTML, by relying on some newer CSS features.

I experimented a bit further with generated content, shadows, and the way the layout of the solar system is implemented. Doing this exposed me to some of the different ways modern browsers are implementing CSS3. I’ve described some of those differences and bugs below.

A scale model of the solar system

The main demo is a scale model of the solar system. It uses 3 different scales: one for the object diameters; one for the distance of the planets from the sun; and one for the orbital period of each planet.

Semantic HTML and Microdata

The HTML is a list where each list item contains a title and description. I’ve included some HTML Microdata to provide hooks for generated content.

<li id="earth" itemscope>
  <h2 itemprop="object">Earth
  <dl>
    <dt>Description</dt>
    <dd itemprop="description">Earth is an ocean planet. Our home world's abundance of water - and life - makes it unique in our solar system. Other planets, plus a few moons, have ice, atmospheres, seasons and even weather, but only on Earth does the whole complicated mix come together in a way that encourages life - and lots of it.</dd>
    <dt>Diameter</dt>
    <dd itemprop="diameter">12,755 <abbr title="kilometers">km</abbr></dd>
    <dt>Distance from sun</dt>
    <dd itemprop="distance">150×10<sup>6</sup> <abbr title="kilometers">km</abbr></dd>
    <dt>Orbital period</dt>
    <dd itemprop="orbit">365<abbr title="days">d</abbr></dd>
  </dl>
</li>

CSS pseudo-elements and generated content

Pseudo-elements are used to produce the planets, Saturn’s ring, the planet names, and to add the scale information.

Given that the scales only make sense when CSS is loaded it isn’t appropriate to have the scales described in the HTML. Both demos use the same HTML but only one of them is a rough scale model. Therefore, in the scale model demo I’ve used generated content to present the ratios and append extra information to the headings.

header h1:after {content:": A scale model";}
header h2:after {content:"Planet diameters 1px : 1,220 km / Distance from sun 1px : 7,125,000 km / Orbital period 1s : 4d";}

#earth dd[itemprop=diameter]:after {content:" (5px) / ";}
#earth dd[itemprop=distance]:after {content:" (22px) / ";}
#earth dd[itemprop=orbit]:after {content:" (91s)";}

Even more complex 3D presentations are likely to be possible using webkit-perspective and other 3D transforms.

Keyboard support

With a little modification it is possible to provide some form of keyboard support so that the additional information and highlighting can be viewed without using a mouse. Doing so requires adding block-level anchors (allowed in HTML5) and modifying some of the CSS selectors.

Modern browser CSS3 inconsistencies

This experiment only works adequately in modern browsers such as Safari 4+, Chrome 4+, Firefox 3.6+ and Opera 10.5+.

Even among the current crop of modern browsers, there are bugs and varying levels of support for different CSS properties and values. In particular, webkit’s box-shadow implementation has issues.

There are a few other unusual :hover bugs in Opera 10.5 (most obvious in the basic demo). It should also be noted that the :hover area remains square in all modern browsers even when you apply a border-radius to the element.

Border radius

There are also a few other peculiarities around percentage units for border radius. Of the modern browsers, a square object with a border-radius of 50% will only produce a circle in Safari 5, Chrome 5, and Firefox 3.6.

Safari 4 doesn’t appear to support percentage units for border radius at all (which is why the CSS in the demos explicitly sets a -webkit-border-radius value for each object). Safari 5 and Chrome 5 do support percentage units for this property. However, Chrome 5 has difficulty rendering a 1px wide border on a large circle. Most of the border simply isn’t rendered.

In Opera 10.5, if you set border-radius to 50% you don’t always get a circle, so I have had to redeclare the border-radius for each object in pixel units.

Opera 10.5’s incorrect rendering of border-radius:50%

It appears that this is one aspect of Opera’s non-prefixed border-radius implementation that is incorrect and in need of fixing.

Box shadow

Safari 4’s inferior box-shadow implementation means that inset shadows are not rendered on the planet bodies. In addition, the second box-shadow applied to Saturn (used to separate the planet from its ring) is completely missing in Safari 4 as it does not support a spread radius value.

Safari 5 and Chrome 5 are better but still problematic. The second box-shadow is not perfectly round as the box-shadow seems to use the pseudo-element’s computed border-radius. Furthermore, Chrome 5 on Windows does not properly support inset box-shadow meaning that the shadow ignores the border-radius declaration and appears as a protruding square.

Safari 5 and Chrome 5 make different mistakes in their rendering of this box-shadow

The use of box-shadow to separate Saturn from the ring isn’t strictly necessary. You can create the separated ring using a border but box-shadow cannot be applied in a way that casts it over a border. Another alternative would be to add a black border around the planet to give the illusion of space between itself and the ring, but all browsers display a few pixels of unwanted background colour all along the outer edge of the rounded border.

I wanted the ring to share the appearance of a shadow being cast on it. Opera 10.5 and Firefox 3.6 get it right. Both webkit browsers get it wrong.




men

CSS image replacement. One more time.

An accessible image replacement method using pseudo-elements and generated-content. This method works with images and/or CSS off, with semi-transparent images, doesn’t hide text from screen-readers or search engines, and provides fallback for IE 6 and IE 7.

Known support: Firefox 1.5+, Safari 3+, Chrome 3+, Opera 9+, IE 8+

What’s wrong with current methods?

The two most widely used image replacement techniques are the Gilder/Levin Method and the Phark Method. Both have different flaws.

The Gilder/Levin Method requires the addition of presentational HTML (an empty span) and doesn’t work with transparent images as the default text shows through. The Phark Method uses a negative text-indent to hide the text and so it is not visible when CSS is on and images are off.

Resurrecting the NIR method

Using pseudo-elements and generated-content as an image replacement technique isn’t a new idea. It was proposed and demonstrated by Paul Nash back in 2006. This is the Nash Image Replacement method.

<h1 class="nir">[content]</h1>
.nir {
   height: 100px; /* height of replacement image */
   padding: 0;
   margin: 0;
   overflow: hidden;
}

.nir:before {
   content: url(image.gif);
   display: block;
}

The height value is equal to that of the replacement image. Setting overflow:hidden ensures that the original content is not visible on screen when the image is loaded. The replacement image is inserted as generated content in the :before pseudo-element which is set to behave like a block element in order to push the element’s original content down.

What about IE 6 and IE 7?

Neither browser supports :before; if you need to support them you’ll have to rely on the Phark method. This can be done using conditional comments or safe IE6/7 hacks to serve alternative styles to legacy versions of IE .

<!--[if lte IE 7]>
<style>
.nir {
   height: 100px;
   padding: 0;
   margin: 0;
   overflow: hidden;
   text-indent: -9000px;
   background: url(image.gif) no-repeat 0 0;
}
</style>
<![endif]-->

Using the NIR method allows you to keep your HTML semantic and deliver improved accessibility to users of modern browsers. The Phark Method can then be served to IE 6 and IE 7.

Improving the NIR method

The first problem with NIR is that if images are disabled all browsers leave whitespace above the element’s content. Opera 10.5 even displays the text string “image”! If the height of the element is small enough this whitespace causes the element’s content to overflow and be partially or completely hidden when images are disabled.

Another consideration is what happens if an image doesn’t exist or fails to load. Safari and Chrome will display a “missing image” icon that cannot be removed. Once again, this can cause the element’s content to overflow and become partially or completely hidden to users.

A more robust version of the NIR method is the following modification:

.nir {
   height: 100px; /* height of replacement image */
   width: 400px; /* width of replacement image */
   padding: 0;
   margin: 0;
   overflow: hidden;
}

.nir:before {
   content: url(image.gif);
   display: inline-block;
   font-size: 0;
   line-height: 0;
}

Setting font-size and line-height to 0 avoids the whitespace problems in all browsers. Setting the element’s width equal to that of the replacement image and getting the pseudo-element to act as an inline-block helps minimise the problems in webkit browsers should an image fail to load.

Ideally browsers would avoid displaying anything in a pseudo-element when its generated-content image fails to load. If that were the case, the original NIR method would be all that is needed.

What about using sprites?

One of the most common uses of image replacement is for navigation. This often involves using a large sprite with :hover and :active states as a background image. It turns out that using sprites is not a problem for modern browsers. When using the modified-NIR method the sprite is included as a generated-content image that is positioned using negative margins.

This is an example that rebuilds the right-hand category navigation from Web Designer Wall using a sprite and the modified-NIR method.

<ul id="nav">
  <li id="nav-item-1"><a href="#non">Tutorials</a></li>
  <li id="nav-item-2"><a href="#non">Trends</a></li>
  <li id="nav-item-3"><a href="#non">General</a></li>
</ul>
/* modified-NIR */

#nav a {
  display: block;
  width: 225px;
  height: 46px;
  overflow: hidden;
}

#nav a:before {
   content:url(sprite.png);
   display:-moz-inline-box; /* for Firefox 1.5 & 2 */
   display:inline-block;
   font-size:0;
   line-height:0;
}

/* repositioning the sprite */

#nav-item-1 a:hover:before,
#nav-item-1 a:focus:before,
#nav-item-1 a:active:before {margin:-46px 0 0;}

#nav-item-2 a:before        {margin:-92px 0 0;}
#nav-item-2 a:hover:before,
#nav-item-2 a:focus:before,
#nav-item-2 a:active:before {margin:-138px 0 0;}

#nav-item-3 a:before        {margin:-184px 0 0;}
#nav-item-3 a:hover:before,
#nav-item-3 a:focus:before,
#nav-item-3 a:active:before {margin:-230px 0 0;}

/* :hover hack for IE8 if no a:hover styles declared */
#nav a:hover {cursor:pointer;}

For some reason IE8 refuses to reposition the image when the mouse is over the link unless a style is declared for a:hover. In most cases you will have declared a:hover styles for the basic links on your webpage, and this is enough. But it is worth being aware of this IE8 behaviour.

The addition of display:-moz-inline-box; is required to reposition the sprite in versions of Firefox prior to Firefox 3.0. They are very rare browsers but I’ve included it in case that level of legacy support is needed.

If you want image replacement in IE 6 and IE 7 the following additional styles can be served to those browsers using conditional comments.

/* Phark IR method */

#nav a {
   text-indent: -9000px;
   background: url(sprite.png) no-repeat;
}

/* repositioning the sprite */

#nav-item-1 a:hover,
#nav-item-1 a:active { background-position: 0 -46px; }

#nav-item-2 a        { background-position: 0 -92px; }
#nav-item-2 a:hover,
#nav-item-2 a:hover  { background-position: 0 -138px; }

#nav-item-3 a        { background-position: 0 -184px; }
#nav-item-3 a:hover,
#nav-item-3 a:active { background-position: 0 -230px; }

/* hack for IE6 */
#nav a:hover { margin: 0; }

The changes are fairly simple. But IE 6 applies the margins declared for a:hover:before to a:hover and so they need to be reset in the styles served to IE 6.

See the modified-NIR (using sprites) demo.




men

Better float containment in IE using CSS expressions

Research into improving the cross-browser consistency of both the “clearfix” and “overflow:hidden” methods of containing floats. The aim is to work around several bugs in IE6 and IE7.

This article introduces a new hack (with caveats) that can benefit the “clearfix” methods and the new block formatting context (NBFC) methods (e.g. using overflow:hidden) of containing floats. It’s one outcome of a collaboration between Nicolas Gallagher (that’s me) and Jonathan Neal.

If you are not familiar with the history and underlying principles behind methods of containing floats, I recommend that you have a read of Easy clearing (2004), Everything you know about clearfix is wrong (2010), and Clearfix reloaded and overflow:hidden demystified (2010).

Consistent float containment methods

The code is show below and documented in this GitHub gist. Found an improvement or flaw? Please fork the gist or leave a comment.

Micro clearfix hack: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+

.cf {
  /* for IE 6/7 */
  *zoom: expression(this.runtimeStyle.zoom="1", this.appendChild(document.createElement("br")).style.cssText="clear:both;font:0/0 serif");
  /* non-JS fallback */
  *zoom: 1;
}

.cf:before,
.cf:after {
  content: "";
  display: table;
}

.cf:after {
  clear: both;
}

Overflow hack (NBFC): Firefox 2+, Safari 2+, Chrome, Opera 9+, IE 6+

.nbfc {
  overflow: hidden;
  /* for IE 6/7 */
  *zoom: expression(this.runtimeStyle.zoom="1", this.appendChild(document.createElement("br")).style.cssText="clear:both;font:0/0 serif");
  /* non-JS fallback */
  *zoom: 1;
}

The GitHub gist also contains another variant of the clearfix method for modern browsers (based on Thierry Koblentz’s work). It provides greater visual consistency (avoiding edge-case bugs) for even older versions of Firefox.

The only difference from existing float-containment methods is the inclusion of a CSS expression that inserts a clearing line-break in IE 6 and IE 7. Jonathan and I found that it helps to resolve some of the visual rendering differences that exist between these browsers and more modern ones. First I’ll explain what some of those differences are and when they occur.

Containing floats in IE 6/7

In IE 6 and IE 7, the most common and robust method of containing floats within an element is to give it “layout” (find out more: On having Layout). Triggering “layout” on an element in IE 6/7 creates a new block formatting context (NBFC). However, certain IE bugs mean that previous float containment methods don’t result in cross-browser consistency. Specifically, this is what to expect in IE 6/7 when creating a NBFC:

  1. The top- and bottom-margins of non-floated child elements are contained within the ancestor element that has been given “layout”. (Also expected in other browsers when creating a NBFC)
  2. The bottom-margins of any right-floated descendants are contained within the ancestor. (Also expected in other browsers when creating a NBFC)
  3. The bottom-margins of any left-floated children are not contained within the ancestor. The margin has no effect on the height of the ancestor and is truncated, having no affect outside of the ancestor either. (IE 6/7 bug)
  4. In IE 6, if the right edge of the margin-box of a left-floated child is within 2px of the left edge of the content-box of its NBFC ancestor, the float’s bottom margin reappears and is contained within the parent. (IE 6 bug)
  5. Unwanted white-space can appear at the bottom of a float-container. (IE 6/7 bug)

There is a lack of consistency between IE 6/7 and other browsers, and between IE 6 and IE 7. Thanks to Matthew Lein for his comment that directed me to this IE 6/7 behaviour. It was also recently mentioned by “Suzy” in a comment on Perishable Press.

IE 6/7’s truncation of the bottom-margin of left-floats is not exposed in many of the test-cases used to demonstrate CSS float containment techniques. Using an IE-only CSS expression helps to correct this bug.

The CSS expression

Including the much maligned <br style="clear:both"> at the bottom of the float-container, as well as creating a NBFC, resolved all these inconsistencies in IE 6/7. Doing so prevents those browsers from collapsing (or truncating) top- and bottom-margins of descendant elements.

Jonathan suggested inserting the clearing line-break in IE 6/7 only, using CSS expressions applied to fictional CSS properties. The CSS expression is the result of many iterations, tests, and suggestions. It runs only once, the first time an element receives the associated classname.

*zoom: expression(this.runtimeStyle.zoom="1", this.appendChild(document.createElement("br")).style.cssText="clear:both;font:0/0 serif");

It is applied to zoom, which is already being used to help contain floats in IE 6/7, and the use of the runtimeStyle object ensures that the expression is replaced once it has been run. The addition of font:0/0 serif prevents the occasional appearance of white-space at the bottom of a float-container. And the * hack ensures that only IE 6 and IE 7 parse the rule.

It’s worth noting that IE 6 and IE 7 parse almost any string used as CSS property. An earlier iteration used the entirely fictitious properties “-ms-inject” or “-ie-x” property to exploit this IE behaviour.

*-ie-x: expression(this.x||(this.innerHTML+='&lt;br style="clear:both;font:0/0">',this.x=1));

However, this expression is evaluated over and over again. Using runtimeStyle instead avoids this. Sergey Chikuyonok also pointed out that using innerHTML destroys existing HTML elements that may event handlers attached to them. By using document.createElement and appendChild you can insert the new element without removing all the events attached to other descendant elements.

Containing floats in more modern browsers

There are two popular methods to contain floats in modern browsers. Creating a new block formatting context (as is done in IE 6/7 when hasLayout is triggered) or using a variant of the “clearfix” hack.

Creating a NBFC results in an element containing any floated children, and will prevent top- and bottom-margin collapse of non-floated children. When combined with the enhanced IE 6/7 containment method, it results in consistent cross-browser float containment.

The other method, known as “clearfix”, traditionally used a single :after pseudo-element to clear floats in a similar fashion to a structural, clearing HTML line-break. However, to prevent the top-margins of non-floats from collapsing into the margins of their float-containing ancestor, you also need to use the :before pseudo-element. This is the approach taken in Thierry Koblentz’s “clearfix reloaded”. In contemporary browsers, the micro clearfix hack is also suitable.

The method presented in this article should help improve the results of cross-browser float containment, whether you predominantly use “clearfix” or the NBFC method. The specific limitations of both the “clearfix” and various NBFC methods (as outlined in Thierry’s articles) remain.

Problems

Using a CSS expression to change the DOM in IE 6/7 creates problems of its own. Obviously, the DOM in IE 6/7 is now different to the DOM in other browsers. This affects any JavaScript DOM manipulation that may depend on :last-child or appending new children.

This is still an experimental work-in-progress that is primarily research-driven rather than seeking to become a practical snippet of production code. Any feedback, further testing, and further experimentation from others would be much appreciated.

Thanks to these people for contributing improvements: Jonathan Neal, Mathias Bynens, Sergey Chikuyonok, and Thierry Koblentz.




men

An introduction to CSS pseudo-element hacks

CSS is a versatile style language that is most frequently used to control the look and formatting of an HTML document based on information in the document tree. But there are some common publishing effects – such as formatting the first line of a paragraph – that would not be possible if you were only able to style elements based on this information. Fortunately, CSS has pseudo-elements and pseudo-classes.

As their names imply, they are not part of the DOM in the way that ‘real’ HTML elements and classes are. Instead, they are CSS abstractions that provide additional, and otherwise inaccessible, information about the document.

This article will discuss the CSS pseudo-elements that are part of CSS 2.1 – :first-letter, :first-line, :before, and :after – and how the :before and :after pseudo-elements can be exploited to create some interesting effects, without compromising the simplicity of your HTML. But first, let’s look at each type of pseudo-element and how to use them in their basic form.

The :first-line and :first-letter pseudo-elements

The :first-line pseudo-element lets you apply styles to the first formatted line of a block container element (i.e., elements with their display property set to block, inline-block, list-item, table-caption, or table-cell). For example:

p:first-line { font-weight: bold; }

…will change the first line of every paragraph to bold. The :first-line pseudo-element can be treated as if it were an extra HTML inline element wrapping only the first line of text in the paragraph.

The :first-letter pseudo-element lets you apply styles to the first letter (and any preceding punctuation) of the first formatted line of a block container element. No other inline content (e.g. an image) can appear before the text. For example:

p:first-letter { float: left; font-size: 200%; }

…will produce a basic ‘drop cap’ effect. The first letter of every paragraph will be floated left, and twice as large as the other letters in the paragraph. The :first-letter pseudo-element can be treated as if it were an extra HTML inline element wrapping only the first letter of text in the paragraph.

The :first-line and :first-letter pseudo-elements can only be attached to block container elements, but the first formatted line can be contained within any block-level descendant (e.g., elements with their display property set to block or list-item) in the same flow (i.e., not floated or positioned). For example, the following HTML fragment and CSS:

<div><p>An example of the first line of text being within a descendant element</p></div>

div:first-line { font-weight: bold; }

…would still result in a bold first line of text, because the paragraph’s text is the first formatted line of the div.

The :before and :after pseudo-elements

The :before and :after pseudo-elements are used to insert generated content before or after an element’s content. They can be treated as if they were extra HTML inline elements inserted just before and after the content of their associated element.

Generated content is specified using the content property which, in CSS 2.1, can only be used in conjunction with the :before and :after pseudo-elements. Furthermore, you must declare the content property in order to generate the :before and :after pseudo-elements.

The content property can take string, url(), attr(), counter() and counters() values. The url() value is used to insert an image. The attr() function returns as a string the value of the specified attribute for the associated element. The counter() and counters() functions can be used to display the value of any CSS counters.

For example, the following HTML fragment and CSS:

<a href="http://wikipedia.org">Wikipedia</a>

a:after { content: " (" attr(href) ")"; }

…would display the value of the href attribute after a link’s content, resulting in the following anchor text for the example above: Wikipedia (http://wikipedia.org). This can be a helpful way to display the destination of specific links in printed web documents.

Keep in mind that CSS is meant for adding presentation and not content. Therefore, the content property should be used with caution.

It’s also worth noting that the :first-letter and :first-line pseudo-elements apply to the first letter and first line of an element including any generated content inserted using the :before and :after pseudo-elements.

Browser support for pseudo-elements

The :first-letter and :first-line pseudo-elements were introduced in CSS1 and there is wide basic support for them. However, IE 6 and IE 7 have particularly buggy implementations; even modern browsers are not entirely consistent in the way that they handle the :first-line and :first-letter pseudo-elements (example bugs).

The :before and :after pseudo-elements were introduced in the CSS 2.1 specification and are fully implemented in Firefox 3.5+, IE 8+, Safari 3+, Google Chrome, and Opera. Modern versions of Firefox even support CSS transitions and animations applied to pseudo-elements. However, legacy browsers like IE 6 and IE 7 do not support the :before and :after pseudo-elements at all.

For more detailed information on pseudo-element browser support, browser bugs, and workarounds, have a look at Sitepoint’s reference and this article on IE 6/7 issues.

In most cases, the :before and :after pseudo-elements can be used as part of a ‘progressive enhancement’ approach to design and development, because IE 6 and IE 7 will simply ignore them altogether. Alternatively, Modernizr now includes a robust feature test for generated content, providing one way to specify fallbacks or enhancements depending on browser support. The important thing is to remember to check what happens in browsers where support is missing.

Alternative ways to use pseudo-elements

Let’s take a look at how the :before and :after pseudo-elements can be used as the basis for some interesting effects. Most of the time, this involves generating empty :before and :after pseudo-elements by declaring an empty string as the value of the content property. They can then be manipulated as if they were empty inline HTML elements, keeping your HTML clean and giving you full control of certain effects from within CSS style sheets.

Simple visual enhancements, like speech bubbles and folded corners, can even be created without the need for images. This relies on the fact that you can create simple shapes using CSS.

Several types of ‘CSS polygons’ can be created as a result of browsers rendering borders at an angle when they meet. This can be exploited to create triangles. For example, the following HTML fragment and CSS:

<div class="triangle"></div>

.triangle {
  width: 0;
  height: 0;
  border-width: 20px;
  border-style: solid;
  border-color: red transparent transparent;
}

…will create a downward pointing, red triangle. By varying the width, height, border-width, border-style, and border-color values you can produce different shapes and control their orientation and colour. For more information, be sure to read Jon Rogan’s summary of the technique.

The more advanced pseudo-element hacks use the extra background canvas afforded by each :before and :after pseudo-element. This can help you crop background images, control the opacity of background images, and ‘fake’ multiple backgrounds and borders in browsers without support for CSS3 multiple backgrounds (e.g., IE 8). Taken to ludicrous extremes, you can even build a whole CSS icon set. To start with, let’s look at some simple effects that can be created without images or presentational HTML.

Creating CSS speech bubbles

In this example, a quote is styled to look like a speech bubble, using CSS. This is done by creating a triangle using a pseudo-element, and then absolutely positioning it in the desired place. By adding position:relative to the CSS styles for the HTML element, you can absolutely position the :after pseudo-element relative to its associated element.

<div class="quote">[Quoted text]</div>

.quote {
  position: relative;
  width: 300px;
  padding: 15px 25px 20px;
  margin: 20px auto;
  font: italic 26px/1.4 Georgia, serif;
  color: #fff;
  background: #245991;
}

.quote:after {
  content: "";
  position: absolute;
  top: 100%;
  right: 25px;
  border-width: 30px 30px 0 0;
  border-style: solid;
  border-color: #245991 transparent;
}

There’s nothing stopping you from adding some CSS3 to further enhance the effect for capable browsers. This could be adding rounded corners to the box or applying a skew transform to the triangle itself. Fiddle with the code in this example.

Creating CSS ‘ribbons’

Using the same principle, you can create a CSS ribbon effect without images or extra HTML. This time the effect uses 2 pseudo-element triangles. The HTML fragment is still very simple.

<div class="container">
    <h1>Simple CSS ribbon</h1>
    <p>[other content]</p>
</div>

You then need to use negative margins to pull the h1 outwards so that it extends over the padding and beyond the boundaries of the container div. The HTML fragment above can be styled using the following CSS:

.container {
  width: 400px;
  padding: 20px;
  margin: 20px auto;
  background: #fff;
}

.container h1 {
  position: relative;
  padding: 10px 30px;
  margin: 0 -30px 20px;
  font-size: 20px;
  line-height: 24px;
  font-weight: bold;
  color: #fff;
  background: #87A800;
}

From here, you only need to add the pseudo-element triangles to create the ‘wrapping’ appearance associated with ribbons. The :before and :after pseudo-elements share many styles, so you can simplify the code by only overriding the styles that differ between the two. In this case, the triangle created with the :after pseudo-element must appear on the opposite side of the heading, and will be a mirror image of the other triangle. So you need to override the shared styles that control its position and orientation.

.container h1:before,
.container h1:after {
  content: "";
  position: absolute;
  top: 100%;
  left: 0;
  border-width: 0 10px 10px 0;
  border-style: solid;
  border-color: transparent #647D01;
}

/* override shared styles */
.container h1:after {
  left: auto;
  right: 0;
  border-width: 0 0 10px 10px;
}

Fiddle with the code in this example.

Creating CSS folded corners

The final example of this form of pseudo-element hack creates a simple CSS folded-corner effect. A pseudo-element’s border properties are set to produce two differently-coloured touching triangles. One triangle is a slightly darker or lighter shade of the box’s background colour. The other triangle matches the background colour of the box’s parent (e.g. white). The pseudo-element is then positioned in the top right corner of its associated element to complete the effect.

.note {
  position: relative;
  padding: 20px;
  margin: 2em 0;
  color: #fff;
  background: #97C02F;
}

.note:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  border-width: 0 16px 16px 0;
  border-style: solid;
  border-color: #658E15 #fff;
}

Varying the size of the borders will vary the size and angle of the folded-corner. Fiddle with the code in this example.

Pseudo background-crop

Although creating polygons with pseudo-elements can produce some popular effects without images, the possibilities are inherently limited. But this is only one type of :before and :after pseudo-element hack. Treated as extra background canvases, they can be used to fill some gaps in existing browser support for CSS features.

One of those features is the cropping of background images. In the future, it’s likely that you’ll be able to crop background images using fragment identifiers, as is proposed in the CSS Image Values Module Level 3 draft. But at the moment no browsers support the use of fragment identifiers with bitmap images. Until they do, you can make use of this CSS 2.1 hack to emulate background image cropping in modern browsers.

The principle behind a ‘pseudo background-crop‘ is to apply a background-image to a pseudo-element rather than directly to an element in the HTML document. One of the applications of this technique is to crop icons that are part of a sprite.

For example, a web app might allow users to ‘save’, ‘edit’, or ‘delete’ an item. The HTML involved might look something like this:

<ul class="actions">
  <li class="save"><a href="#">Save</a></li>
  <li class="edit"><a href="#">Edit</a></li>
  <li class="delete"><a href="#">Delete</a></li>
</ul>

To enhance the appearance of these ‘action’ links, it is common to see icons sitting alongside the anchor text. For argument’s sake, let’s say that the relevant icons are part of a sprite that is organised using a 16px × 16px grid.

The :before pseudo-element – with dimensions that match the sprite’s grid unit – can be used to crop and display each icon. The sprite is referenced as a background image and the background-position property is used to control the precise positioning of each icon to be shown.

.actions a:before {
  content: "";
  float: left;
  width: 16px;
  height: 16px;
  margin: 0 5px 0 0;
  background: url(sprite.png);
}

.save a:before { background-position: 0 0; }
.edit a:before { background-position: -16px 0; }
.delete a:before { background-position: -32px 0; }

Using pseudo-elements like this helps to avoid the need to either add liberal amounts of white space to sprites or use empty HTML elements to do the cropping. Fiddle with the code in this example.

Pseudo background-position

The CSS 2.1 specification limits the values of background-position to horizontal and vertical offsets from the top-left corner of an element. The CSS Backgrounds and Borders Module Level 3 working draft includes an improvement to the background-position property to allow offsets to be set from any side. However, Opera 11+ is currently the only browser to have implemented it.

But by using pseudo-elements, it’s possible to emulate positioning a background image from any side in any browser with adequate CSS 2.1 support –’pseudo background-position‘.

Once a pseudo-element is created, it must be absolutely positioned in front of the associated element’s background but behind its content, so as not to prevent users from being able to select text or click on links. This is done by setting a positive z-index on the element and a negative z-index on the pseudo-element.

#content {
  position: relative;
  z-index: 1;
}

#content:before {
  content: "";
  position: absolute;
  z-index: -1;
}

Now the pseudo-element can be sized and positioned to sit over any area within (or beyond) the element itself, without affecting its content. This is achieved by using any combination of values for the top, right, bottom, and left positional offsets, as well as the width, and height properties. It is the key to their flexibility.

In this example, a 200px × 300px background image is applied to the pseudo-element, which is also given dimensions that match those of the image. Since the pseudo-element is absolutely positioned, it can be offset from the bottom and right of the associated HTML element.

#content {
  position: relative;
  z-index: 1;
}

#content:before {
  content: "";
  position: absolute;
  z-index: -1;
  bottom: 10px;
  right: 10px;
  width: 200px;
  height: 300px;
  background: url(image.jpg);
}

Many other hacks and effects are possible using the :before and :after pseudo-elements, especially when combined with CSS3. Hopefully this introduction to pseudo-elements, and how they can be exploited, will have inspired you to experiment with them in your work.

The future of pseudo-elements

The way that pseudo-elements are used will continue to change as CSS does. Some new applications will emerge, and existing ones will fade away as browser implementation of ‘CSS3 modules’ continues to improve.

Generated content and pseudo-elements themselves are likely to undergo changes too. The CSS3 Generated and Replaced Content Module introduced a two-colon format for pseudo-elements (i.e., ::before) to help distinguish between pseudo-classes and pseudo-elements. But for compatibility with previous levels of CSS, pseudo-elements do not require two colons. Most modern browsers support both formats, but it is not supported by IE 8 and the single-colon format ensures greater backwards compatibility.

The proposed extensions to pseudo-elements included the addition of nested pseudo-elements (::before::before), multiple pseudo-elements (::after(2)), wrapping pseudo-elements (::outside), and the ability to insert pseudo-elements into later parts of the document (::alternate). However, the CSS3 Generated and Replaced Content Module is undergoing significant changes.

This article was originally published in .net magazine in April 2011




men

Another CSS image replacement technique

A new image replacement technique was recently added to the HTML5 Boilerplate project. This post explains how it works and how it compares to alternative image replacement techniques.

[15 December 2012] This technique is no longer used in HTML5 Boilerplate. It’s been replaced by another, more reliable approach.

Here’s the CSS behind the recent update to the image replacement helper class in HTML5 Boilerplate. It has also made its way into the Compass framework.

.ir {
  font: 0/0 a;
  text-shadow: none;
  color: transparent;
}

What does each declaration do?

  • font:0/0 a – a shorthand property that zeros out the font size and line-height. The a value acts as a very short font-family (an idea taken from the BEM implementation of this method). The CSS validator complains that using 0/0 in the shorthand font property is not valid, but every browser accepts it and this appears to be an error in the validator. Using font:0px/0 a passes validation but it displayed as font:0/0 a in the code that the validator flags as valid.
  • text-shadow:none – makes sure that any inherited text shadow is removed for the text. This prevents the chance of any text shadow colors showing over the background.
  • color:transparent – needed for browsers than don’t completely crush the text to the point of being invisible. Safari 4 (extremely rare) is an example of such a browser. There may also be mobile browsers than require this declaration. IE6/7/8 don’t recognise this value for color, but fortunately IE7/8 don’t show any trace of the text. IE6 shows a faint trace.

In the HTML5 Boilerplate image replacement helper, we’ve also removed any border and background-color that may be on the element. This makes it easier to use the helper class on elements like button or with links that may included background or border properties as part of a design decision.

Benefits over text-indent methods

The new technique avoids various problems with any text-indent method, including the one proposed by Scott Kellum to avoid iPad 1 performance problems related to large negative text indents.

  • Works in IE6/7 on inline-block elements. Techniques based on text indentation are basically “broken”, as shown by this test case: http://jsfiddle.net/necolas/QZvYa/show/
  • Doesn’t result in any offscreen box being created. The text-indent methods result in a box being drawn (sometimes offscreen) for any text that have been negatively or positively indented. It can sometimes cause performance problems but the font-based method sidesteps those concerns.
  • No need to specify a text-alignment and hide the overflow since the text is crushed to take up no space.
  • No need to hide br or make all fallback HTML display:inline to get around the constraints of using a text indentation. This method is not affected by those problems.
  • Fewer styles are needed as a result of these improvements.

Drawbacks

No image replacement hack is perfect.

  • Leaves a very small trace of the text in IE6.
  • This approach means that you cannot use em units for margins on elements that make use of this image replacement code. This is because the font size is set to 0.
  • Windows-Eyes has a bug that prevents the reading of text hidden using this method. There are no problems with all other screenreaders that have been tested. Thanks to @jkiss for providing these detailed results and to @wilto for confirming this technique works for JAWS 12 in IE 6/7/8 and Firefox 4/5/6.
  • Like so many IR methods, it doesn’t work when CSS is loaded but images are not.
  • Text may not be hidden if a visitor is using a user style sheet which has explicitly set important font-size declarations for the element type on which you have applied the IR class.

It’s worth noting that the NIR image replacement technique avoids these drawbacks, but lacks support in IE6/7.

Closing comments

I’ve been using this technique without significant problems for nearly a year, ever since Jonathan Neal and I used it in a clearfix experiment. The BEM framework also makes use of it for their icon components. The core idea was even proposed back in 2003 but the browser quirks of the day may have prevented wider use.

If you come across any problems with this technique, please report them at the HTML5 Boilerplate GitHub issue tracker and include a test case when appropriate.

Translations




men

A simple Git deployment strategy for static sites

This is how I am deploying the build of my static website to staging and production domains. It requires basic use of the CLI, Git, and SSH. But once you’re set up, a single command will build and deploy.

TL;DR: Push the static build to a remote, bare repository that has a detached working directory (on the same server). A post-receive hook checks out the files in the public directory.

Prerequisites

  • A remote web server to host your site.
  • SSH access to your remote server.
  • Git installed on your remote server (check with git --version).
  • Generate an SSH key if you need one.

On the server

Set up password-less SSH access

First, you need to SSH into your server, and provide the password if prompted.

ssh user@hostname

If there is no ~/.ssh directory in your user’s home directory, create one: mkdir ~/.ssh.

Next, you need to copy your public SSH key (see “Generate an SSH key” above) to the server. This allows you to connect via SSH without having to enter a password each time.

From your local machine – assuming your public key can be found at ~/.ssh/id_rsa.pub – enter the following command, with the correct user and hostname. It will append your public key to the authorized_keys file on the remote server.

ssh user@hostname 'cat >> ~/.ssh/authorized_keys' < ~/.ssh/id_rsa.pub

If you close the connection, and then attempt to establish SSH access, you should no longer be prompted for a password.

Create the remote directories

You need to have 2 directories for each domain you want to host. One for the Git repository, and one to contain the checked out build.

For example, if your domain were example.com and you also wanted a staging environment, you’d create these directories on the server:

mkdir ~/example.com ~/example.git

mkdir ~/staging.example.com ~/staging.example.git

Initialize the bare Git repository

Create a bare Git repository on the server. This is where you will push the build assets to, from your local machine. But you don’t want the files served here, which is why it’s a bare repository.

cd ~/example.git
git init --bare

Repeat this step for the staging domain, if you want.

Write a post-receive hook

A post-receive hook allows you to run commands after the Git repository has received commits. In this case, you can use it to change Git’s working directory from example.git to example.com, and check out a copy of the build into the example.com directory.

The location of the working directory can be set on a per-command basis using GIT_WORK_TREE, one of Git’s environment variables, or the --work-tree option.

cat > hooks/post-receive
#!/bin/sh
WEB_DIR=/path/to/example.com

# remove any untracked files and directories
git --work-tree=${WEB_DIR} clean -fd

# force checkout of the latest deploy
git --work-tree=${WEB_DIR} checkout --force

Make sure the file permissions on the hook are correct.

chmod +x hooks/post-receive

If you need to exclude some files from being cleaned out by Git (e.g., a .htpasswd file), you can do that using the --exclude option. This requires Git 1.7.3 or above to be installed on your server.

git --work-tree=${WEB_DIR} clean -fd --exclude=<pattern>

Repeat this step for the staging domain, if you want.

On your local machine

Now that the server configuration is complete, you want to deploy the build assets (not the source code) for the static site.

The build and deploy tasks

I’m using a Makefile, but use whatever you feel comfortable with. What follows is the basic workflow I wanted to automate.

  1. Build the production version of the static site.

    make build
    
  2. Initialize a new Git repo in the build directory. I don’t want to try and merge the new build into previous deploys, especially for the staging domain.

    git init ./build
    
  3. Add the remote to use for the deploy.

    cd ./build
    git remote add origin ssh://user@hostname/~/example.git
    
  4. Commit everything in the build repo.

    cd ./build
    git add -A
    git commit -m "Release"
    
  5. Force-replace the remote master branch, creating it if missing.

    cd ./build
    git push -f origin +master:refs/heads/master
    
  6. Tag the checked-out commit SHA in the source repo, so I can see which SHA’s were last deployed.

    git tag -f production
    

Using a Makefile:

BUILD_DIR := ./build
STAGING_REPO = ssh://user@hostname/~/staging.example.git
PROD_REPO = ssh://user@hostname/~/example.git

install:
    npm install

# Deploy tasks

staging: build git-staging deploy
    @ git tag -f staging
    @ echo "Staging deploy complete"

prod: build git-prod deploy
    @ git tag -f production
    @ echo "Production deploy complete"

# Build tasks

build: clean
    # whatever your build step is

# Sub-tasks

clean:
    @ rm -rf $(BUILD_DIR)

git-prod:
    @ cd $(BUILD_DIR) && 
    git init && 
    git remote add origin $(PROD_REPO)

git-staging:
    @ cd $(BUILD_DIR) && 
    git init && 
    git remote add origin $(STAGING_REPO)

deploy:
    @ cd $(BUILD_DIR) && 
    git add -A && 
    git commit -m "Release" && 
    git push -f origin +master:refs/heads/master

.PHONY: install build clean deploy git-prod git-staging prod staging

To deploy to staging:

make staging

To deploy to production:

make prod

Using Make, it’s a little bit more hairy than usual to force push to master, because the cd commands take place in a sub-process. You have to make sure subsequent commands are on the same line. For example, the deploy task would force push to your source code’s remote master branch if you failed to join the commands with && or ;!

I push my site’s source code to a private repository on BitBucket. One of the nice things about BitBucket is that it gives you the option to prevent deletions or history re-writes of branches.

If you have any suggested improvements, let me know on Twitter.




men

Bihar government to do random testing of migrants on arrival

TrueNat machines will be used for the first time in the State for virus screening




men

Coronavirus | Tripura State Rifles men risk infection from BSF soldiers

State health officials are planning extensive tests




men

Working women beaten up in paddy field




men

Strategic information management [electronic resource] : challenges and strategies in managing information systems / R.D. Galliers and D.E. Leidner

Galliers, Robert, 1947-




men

A strategic-oriented implementation of projects [electronic resource] / Mihály Görög, PhD, Professor of Project Management

Görög, Mihály, 1951-




men

Strategic risk management [electronic resource] : new tools for competitive advantage in an uncertain age / Paul C. Godfrey, [and three others]

Godfrey, Paul C., author




men

Strategic value management [electronic resource] : stock value creation and the management of the firm / Juan Pablo Stegmann

Stegmann, Juan Pablo




men

Strategische personalentwicklung in der praxis [electronic resource] : instrumente, erfolgsmodelle, checklisten, praxisbeispiele. / Christine Wegerich

Wegerich, Christine, author




men

Strategisches IT-Management [electronic resource] / Josephine Hofmann, Matthias Knoll (Hrsg.)




men

Strategisches management für KMU [electronic resource] : unternehmenswachstum durch (r)evolutionäre Unternehmensführung / Gerrit Hamann

Hamann, Gerrit, author




men

Strategisches management und marketing [electronic resource] : markt- und wettbewerbsanalyse, strategische frühaufklärung, portfolio-management / Edgar Kreilkamp

Kreilkamp, Edgar




men

Streamlining business requirements [electronic resource] : the XCellR8 approach / Gerrie Caudle

Caudle, Gerrie




men

The subjective well-being module of the American Time Use Survey [electronic resource] : assessment for its continuation / Panel on Measuring Subjective Well-Being in a Policy-Relevant Framework, Committee on National Statistics, Division of Behavioral an




men

Succeeding in the project management jungle [electronic resource] : how to manage the people side of projects / Doug Russell

Russell, Doug




men

Successes and failures of knowledge management [electronic resource] / edited by Jay Liebowitz, Distinguished Chair of Applied Business and Finance, Harrisburg University of Science and Technology, Harrisburg, Pennsylvania




men

Successful management guidelines (collection) [electronic resource] / Martha I. Finney, Stephan Robbins

Finney, Martha I., author




men

Successful project management [electronic resource] : how to complete projects on time, on budget, and on target / Michael S. Dobson

Dobson, Michael Singer, author




men

Supply chain management [electronic resource] / Vinod V. Sople

Sople, Vinod V., author




men

Supply chain management at warp speed [electronic resource] : integrating the system from end to end / Eli Schragenheim, H. William Dettmer, J. Wayne Patterson

Schragenheim, Eli




men

Supply chain management for engineers [electronic resource] / Samuel H. Huang

Huang, Samuel H., author




men

Supply chain management process standards [electronic resource] : deliver processes / Council of Supply Chain Management Professionals

Council of Supply Chain Management Professionals, author




men

Supply chain management talent development [electronic resource] : acquire, develop, and advance processes / Council of Supply Chain Management Professionals

Council of Supply Chain Management Professionals, author




men

Sustainability in supply chain management (collection) [electronic resource] / Peter A. Soyka, Robert Palevich, Steven M. Leon

Soyka, Peter A., 1958- author




men

System center 2012 R2 configuration manager [electronic resource] : supplement to system center 2012 configuration manager (SCCM) unleashed / Kerrie Meyler, Jason Sandys, Greg Ramsey

Meyler, Kerrie, author




men

System center operations manager 2007 R2 unleashed [electronic resource] : supplement to System center operations manager 2007 unleashed / Kerrie Meyler ... [et al.]




men

The talent assessment and development pocket tool kit [electronic resource] : how to get the most out of your best people / Brenda Hampel and Anne Bruce

Hampel, Brenda




men

Testdaten und Testdatenmanagement [electronic resource] : Vorgehen, Methoden und Praxis / Janet Albrecht-Zölch

Albrecht-Zölch, Janet, author




men

Thinkers 50 business thought leaders from India [electronic resource] : the best ideas on innovation, management, strategy, and leadership / Stuart Crainer + Des Dearlove

Crainer, Stuart




men

Thinkers 50 management [electronic resource] : cutting edge thinking to engage and motivate your employees for success / Stuart Crainer + Des Dearlove

Crainer, Stuart




men

Time management in an instant [electronic resource] : 60 ways to make the most of your day / Karen Leland & Keith Bailey

Leland, Karen




men

Comment tirer profit de l'intelligence collective? [electronic resource] : pratiques de management et dynamiques d'équipe / par Véronique Bronckart

Bronckart, Véronique, author




men

Too good to fail? [electronic resource] : how management gets it wrong and how you can get it right / Jan Filochowski

Filochowski, Jan




men

Bank management (Online)




men

The top 50 management dilemmas [electronic resource] : fast solutions to everyday challenges / Sona Sherratt and Roger Delves

Sherratt, Sona




men

Total quality management [electronic resource] / Poornima M. Charantimath

Charantimath, Poornima M., author




men

Total quality management and just-in-time purchasing [electronic resource] : their effects on performance of firms operating in the U.S. / Hale Kaynak

Kaynak, Hale, 1956-




men

Total Quality Management [electronic resource] : Key Concepts and Case Studies / D.R. Kiran

Kiran, D. R., author




men

Total quality of management [electronic resource] / Tapan K. Bose

Bose, Tapan K., author




men

Training and development for dummies [electronic resource] / by Elaine Biech, CPLP Fellow ; foreword by Tony Bingham, President and CEO, Association for Talent Development

Biech, Elaine




men

The triple constraints in project management [electronic resource] / Michael S. Dobson

Dobson, Michael Singer, author




men

Journal of service management research (Online)




men

Management (Auckland, N.Z. : Online)




men

Unearthing business requirements [electronic resource] : elicitation tools and techniques / Rosemary Hossenlopp, Kathleen Hass

Hossenlopp, Rosemary, 1958-




men

Pharmacy practice management quarterly (Online)