Michael Gearon

CSS url()

Michael Gearon

Last updated on

CSS3 Pseudo Element

The use cases of url() in CSS are huge, here are most of the properties the url() function can be included as a value: background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-image-source, mask, mask-image, src as part of a @font-face block, and @counter-style/symbol

Relative

In it’s simplest form the function can be used to load a resource like a background image:

div {
  background-image: url(test.png);
}

In this use case I used a relative URL, which searches the file in the folder where the CSS file is defined. So if the asset (test.png) is in the same folder as the CSS file then it would fine the image.

I could go one level back, this could be useful if your images are stored outside of your CSS folder:

section {
  background-image: url(../test.png);
}

or go into a folder if the assets are in a subfolder:

section {
  background-image: url(subfolder/test.png);
}

Root level

You could load a file starting from the root of the domain where the CSS is hosted:

section {
  background-image: url(/test.png);
}

Absolute

Alternatively you could use an absolute URL to load an external resource:

section {
  background-image: url(https://mysite.com/test.png);
}

More guides on CSS

Michael Gearon

Written by
Michael Gearon

Michael Gearon is a Senior Interaction Designer at Companies House in Cardiff. Previously Mike was a product designer at the GoCo Group including GoCompare, MyVoucherCodes and WeFlip. As well working for brands in South Wales like BrandContent and HEOR.