TL;DR — When creating website layouts, you can manipulate the look and behavior of two-dimensional CSS images using various properties.
Contents
Using images in CSS
It's hard to avoid using pictures when you're working with layouts and designs. In CSS, images can be used for backgrounds, borders and a variety of other properties:
body {
background-image: url(https://cdn.bitdegree.org/learn/pom-laptop.png?raw=true),
url(https://cdn.bitdegree.org/learn/space%20gif.gif?raw=true);
}
Images in CSS come in two types:
- Plain images added by defining a source (e.g., a URL)
- Dynamically generated images created by using CSS properties (e.g., gradients)
Properties to use with CSS images
In the table below, you can check the most popular properties that you can use to modify the look of your CSS images:
Property | Definition |
---|---|
border | Draw a border around the image in CSS |
outline | Draw an outline around the image in CSS |
margin | Add space around the image outside the borders |
padding | Add space around the image inside the borders |
height | Manipulate the height of the image in CSS |
width | Manipulate the width of the image in CSS |
opacity | Manipulate the opacity of the image in CSS |
Note: by using the resize property, you can specify whether the user can change the image size in CSS.
CSS image sprites explained
An image sprite is essentially a set of multiple images in a single image file. This saves time and bandwidth, as you don't need to issue multiple server requests to load multiple CSS images separately.
Sprites were created by the video game industry, as fast loading time is crucial for players. The main idea is to have one big image and use parts of it as needed. In the example below, you can see how to define a particular part of the sprite you wish to use:
#container {
width: 64px;
height: 64px;
background: url('https://cdn.bitdegree.org/learn/css-image-sprite-3.png?9dd3e0b4') 10px 20px;
background-repeat: none;
}
CSS images: useful tips
- While using sprites saves time, it does make updating CSS images in your webpage more complicated. Try not to use them where you'll be needing constant graphics updates.
- Assistive technologies do not understand images, so make sure not to use background images for crucial info and include alternative texts for illustrations.