freeCodeCamp/guide/english/css/css-images/index.md

4.2 KiB

title
CSS Images

CSS Images

This helps in adding an image to a website. CSS can handle images like JPG, PNG or other raster format. There are two types images: plain images which are sometimes referenced with a url, and dynamically generated images which are generated by some element.

Code Sample

<img src="picture.jpg" alt="Picture" width="100" height="100">

  • src: It consists the value of the path to the required image.
  • alt: This is a text description of the image and is useful if the image cannot be viewed by a visitor. It also allows the image on your page to rank in image search results for search engines such as Google.
  • width: This specifies a width for the image(can be percent or px or auto).
  • height: This specifies a height for the image(can be percent or px or auto).

CSS Defaults

The img element will be rendered by default in most browsers to be displayed as an inline-block display type unless specified otherwise.

img {
  display: inline-block;
}

More Information:

It is advised to change any one parameter, either height or width, to get a proportionate image. Changing both dimensions results in forced scaling and is not advisable.

Example: Both of these will result in a proportionate image

<img src="picture.jpg" alt="Picture" width="100">
    
//  or
     
<img src="picture.jpg" alt="Picture" height="100">
Properties

image-orientation image-rendering object-fit object-position

Functions

linear-gradient() radial-gradient() repeating-linear-gradient() repeating-radial-gradient() element()

Datatypes

<image> <uri>

Image Sprites

An image sprite is a collection of images put into a single image. A web page with many images can take a long time to load and generates multiple server requests. Using image sprites will reduce the number of server requests and save bandwidth.

#home {
    width: 46px;
    height: 44px;
    background: url(img_navsprites.gif) 0 0;
}

More Info: