Cet article est également disponible en français

There’s not a lot of information about replaced HTML elements to be found online. Neither is the topic addressed in any web development book that I’m aware of. That’s is unfortunate… because, from my experience, knowing the limitations of replaced elements would have saved me a lot of stress when I started experimenting with advanced CSS.

Essentially, replaced elements are HTML elements that have a predetermined width and height, without benefit of . Another way of thinking of replaced elements is “any tag that has its content replaced by an outside source”. <img> and <video> are obvious examples, but many form elements, such as <input>, are also replaced. For example, whezn you insert the following code on a page:

<input type="text">

… the input just shows up, at a size that is suitable for single-line text-input. That doesn’t mean you shouldn’t add extra attributes and values to the element, or that you can’t apply CSS to it, just that the browser replaces that tag with an object of a predetermined size by default. The same happens with <img>:

<img src="bison.jpg" alt="Plains bison">

Without any extra information, bison.jpg will be loaded onto the page and the img tag replaced with whatever content bison.jpg contains, at the picture’s natural width and height.

<br>, <hr> and <object> are all replaced elements, as are <input>, <button>, <textrarea>. <video> and <iframe>. <audio> and are also replaced elements under some circumstances.

If you can still use CSS to alter the appearance of these elements, how does the fact that they are “replaced” make any difference? Because of two vital rules:

  1. You cannot apply generated content to replaced elements. That is, you cannot apply the pseudo-element selectors :before or :after to them.

    Think about it. Wouldn’t it be great to be able to auto-generate captions for images in CSS? You have the information right there, in the image’s alt and title! In theory, all you’d need to do is this:

    img:after {
    	content: attr(alt);
    }

    That would be perfect! You could just display the alt value of the image directly on the page, and not have to worry about <figcaption> or definition lists for images at all. But it can’t be done. The <img> tag is already replaced content: you can’t generate more content on top of that with CSS.

    Bottom line: if you can’t get a result from directly applying :before or :after to a tag, it’s a replaced element.

    (There are still methods to automatically add captions to images, usually with or . See the Image Gallery reading list for more info.)

  2. If the CSS for a replaced element like does not load, its dimensions default to 300 × 150 pixels.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.