Skip to main content

CSS Backgrounds

The CSS background properties add background effects to elements.

In these chapters you will learn about these background properties:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position
  • background (the shorthand property)

CSS background-color

The background-color property sets the background color of an element.

A color is usually written as a color name (like red), a HEX value (like #ff0000), or an RGB value (like rgb(255,0,0)).

Example

The whole page gets a light blue background.

Prompt
An HTML page that sets the page background color with CSS. In an internal <style> block, set the body background-color to lightblue. Add a heading and a paragraph.
Output: complete HTML page

Other Elements

You can set the background color of any HTML element, not just the page.

Example

The <h1>, <div>, and <p> elements each get a different background color.

Prompt
An HTML page that sets different background colors for different elements. In an internal <style> block, make <h1> green, <div> lightblue, and <p> yellow. Add one of each element in the body so the three background colors show.
Output: complete HTML page

Opacity / Transparency

The opacity property sets how transparent an element is, from 0.0 to 1.0. A lower value is more transparent.

Note: When you use opacity on an element, its child elements get the same transparency too. This can make text inside a faded element hard to read.

Example

The div has opacity 0.3, so both its background and its text are faded.

Prompt
An HTML page that uses the opacity property to make an element semi-transparent. In an internal <style> block, give a <div> a green background and opacity of 0.3. Put some text inside the div so the lowered opacity (which also affects the text) is visible.
Output: complete HTML page

Transparency using RGBA

If you do not want the child elements to fade, use an RGBA color instead. RGBA sets the opacity of the background color only, not the text.

An RGBA color is written as rgba(red, green, blue, alpha). The alpha is a number from 0.0 (fully transparent) to 1.0 (fully solid).

Example

The div background is 30% transparent, but the text stays fully readable.

Prompt
An HTML page that uses an RGBA background color so only the background is transparent, not the text. In an internal <style> block, give a <div> a background of rgba(0, 128, 0, 0.3) (green at 30% opacity). Put some text inside the div, which should stay fully readable.
Output: complete HTML page

The CSS Background Color Property

The property covered on this page is background-color, which sets the background color of an element.