2 min read

Colors and Backgrounds

CSS provides properties to set the color of text and the background of elements.

1. CSS Colors

Colors in CSS can be specified in various ways.

Color Names

There are 140 standard color names supported by all modern browsers.

h1 { color: tomato; }
p { color: DodgerBlue; }

Hexadecimal (Hex)

A hex code is a 6-digit representation of a color. The first two digits represent red, the next two green, and the last two blue.

p { color: <a href='/?search=%23ff6347' class='obsidian-tag'>#ff6347</a>; } /* Tomato */

RGB / RGBA

RGB color values are supported in all browsers. An RGB color value is specified with: rgb(red, green, blue). Each parameter defines the intensity of the color as an integer between 0 and 255. RGBA adds an Alpha channel for opacity (0.0 is fully transparent, 1.0 is fully opaque).

p { color: rgb(255, 99, 71); }
div { background-color: rgba(255, 99, 71, 0.5); }

HSL / HSLA

HSL stands for Hue, Saturation, and Lightness.

  • Hue: Degree on the color wheel (0 to 360). 0 is red, 120 is green, 240 is blue.
  • Saturation: Percentage value. 0% is shade of gray, 100% is full color.
  • Lightness: Percentage value. 0% is black, 50% is normal, 100% is white.
p { color: hsl(9, 100%, 64%); }
div { background-color: hsla(9, 100%, 64%, 0.5); }

2. CSS Backgrounds

The CSS background properties are used to define the background effects for elements.

background-color

Specifies the background color of an element.

body {
  background-color: lightblue;
}

background-image

Specifies an image to use as the background of an element. By default, the image is repeated so it covers the entire element.

body {
  background-image: url("paper.gif");
}

background-repeat

Sets if/how a background image will be repeated.

  • repeat: Repeat both vertically and horizontally (default).
  • repeat-x: Repeat only horizontally.
  • repeat-y: Repeat only vertically.
  • no-repeat: Do not repeat.

background-position

Specifies the position of the background image (e.g., top right, center, 10px 50%).

background-attachment

Sets whether a background image scrolls with the rest of the page, or is fixed.

  • scroll: The background scrolls with the page (default).
  • fixed: The background is fixed (doesn't move).

background-size (CSS3)

Specifies the size of the background image.

  • cover: Scale the background image to be as large as possible so that the background area is completely covered.
  • contain: Scale the image to the largest size such that both its width and its height can fit inside the content area.

Shorthand Property

To shorten the code, it is possible to specify all the background properties in one single property.

body {
  background: <a href='/?search=%23ffffff' class='obsidian-tag'>#ffffff</a> url("img_tree.png") no-repeat right top;
}

programming/css/css programming/css/box-model programming/css/gradients