What is the CSS url() function?

What is a URL?

Uniform Resource Location (URL) is an internet and WWW concept, and it is an address with which resources can be shared among devices on the internet. It is simply a resource locator. In CSS, some resources which need to be used can be in the host or somewhere else on the internet.

With the url() function, you can easily add this resource to your style.

About the CSS url() function

This function will basically include the indicated file to a Stylesheet. This file can be on the same host/server as the webpage/style or another server on the internet. In any case, the parameter of this function can be an absolute URL, a relative URL, or a data URI of resource to be included.

The url() can be included as a value for a couple of things like:

  • background and background-image.
  • border, border-image, border-image-source.
  • content
  • cursor
  • filter
  • list-style and list-style-image
  • mask, mask-image and offset-path.

Syntax

url("address_of_file")

Parameters

This function requires only a single parameter, which is the file address. This file address can be relative or absolute addresses or URI of any resource needed. This resource can be an image in png, jpeg, gif, or even svg formats or any other file.

Some sample use case

  • A url used in the background property. It provides an image for the background of a selected element.
.maindiv{
  background: url("mainimg.png") #00D no-repeat fixed;
}
  • URL provides an image to be as a list bullet.
ul {
  list-style: square url("http://www.unsplash.com/star00291MN.png");
}

  • Used to import styles and fonts to a Stylesheet.
@import url("https://www.freestyles.com/style.css");

In these instances and more, you can use CSS’s url() function.

Explanation

The image that covered the background of our code output below is from unsplash.com, and it is linked to using the CSS URL background-image property value as indicated in the CSS file. The background-repeat: no-repeat value and the background-size: cover property value will make the image not show multiple times on the screen and cover the whole screen, respectively.

Free Resources