Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Explore Great Enhancement And Optimization With CSS Image

Good content is essential to a remarkable and engaging user interface. In web design, appealing aesthetics and compelling content are vital to enhancing user engagement. This symbiotic relationship between content and design is made possible through images, forging a link between users and the tangible world. This connection creates a unique brand identity.

However, just adding images won’t do the trick. That is where using CSS to style images becomes crucial to presenting visually engaging web content. By applying CSS styles to images, developers can unleash their creativity and transform pictures into visually appealing elements that captivate the audience and leave a lasting impression.

This article will discuss web images, the best and most accessible way to display pictures, and how to apply image styling to achieve interactive and enhanced user engagement.

Before we get started, explore PureCode AI-generated custom components designed for CSS3 if you’re working on a project and want to bypass crafting the UI components manually.

Exploring Images on the Web

Overview of Web images

An image is a visual representation of information. Digital images, on the other hand, are visual representations of information in a digital format. Digital images are composed of pixels that contain data, collectively forming the visual content. Furthermore, web images are a type of digital images that are intended and optimized for use on the web. These images are crucial to web design and content, enhancing visual appeal, improving user experience, and conveying information effectively. Generally, images are best for communicating lots of information in a short time. Therefore, choosing the right images plays a huge role in connecting your target audience to your brand.

This choice involves finding a balance between file size and image quality. The higher the quality, the better the image resolution, but the larger the file size. Heavy images can increase your page loading time, which hurts your user experience. Therefore, it is best to use photos at their display dimensions. For instance, the original image has dimensions of 2820px by 3230px and a file size of 5 megabytes. Resizing the original photo is recommended if the specified display dimension is 800px by 600px. This process will considerably reduce the file size while preserving the image quality.

Supported Image formats

The choice of image format can also balance image quality with efficient file size, improving page loading and user experience. Therefore, choosing an appropriate and consistent image file format is essential. The supported formats include the following:

  • JPG/JPEG

  • PNG

  • SVG

  • GIF

  • WebP

JPG/JPEG

JPG/JPEG is a graphic image file with a high-level compression algorithm that allows it to retain most colors in a photograph. JPGs can have relatively small sizes and are well-suited for photos and images with gradients because they support many colors.

PNG

PNGs (Portable Network Graphics) are image files with a pixel-based compression format. The PNG format is relatively larger because it contains more information. It can undergo a lossless compression, i.e., all information in PNGs is restored when decompressed. They are also suitable for transparent backgrounds.

GIF

GIF (Graphics Interchange Format) is a graphic image type capable of simple animation and lossless compression. However, they are the least recommended photos because they have a limited color palette of 256 colors.

SVG

SVG (Scalar Vector Graphics) is a vector-based compression file format mainly used for icons and illustrations. SVGs are scalable without losing quality since SVGs do not depend on unique pixels. Furthermore, their Extensible Markup Language (XML) format enables them to be embedded within HTML code, making them searchable and indexable.

WebP

WebP is a modern image format developed by Google. They offer better compression for images with support for higher color depths, animated frames, and transparency to create smaller, richer images that make the web faster. WebP is an excellent choice for both photos and motion images.

Displaying an Image

No image will be visible on a webpage if it isn’t displayed. Understanding how to display an image properly is vital for the visual appeal and user experience. This section will discuss how to display photos and the most effective approach to using these images to achieve optimal user experience.

Basics of displaying images

There are several ways to display an image on a webpage, these methods include the following:

  • Using the <img> element

  • Using CSS background-image property

Using the <img> element

To display an image using the self-closing <img> tag, you need to specify the URL or file path of the image using the src attribute and provide a description of the image with the alt attribute. The following code example shows how to achieve this feat:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Using the img tag</title>
    <style>
      h1 {
        text-align: center;
      }

      img {
        max-width: 100%;
        height: auto;
      }
    </style>
  </head>
  <body>
    <h1>Displaying an image with the HMTL <code>img</code> element</h1>
    <img
      src="https://images.unsplash.com/photo-1473172707857-f9e276582ab6?q=80&w=1080&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
      alt="A man standing on stone looking at sunset"
    />
  </body>
</html>
A visual illustration of an image rendered using HTML img element

Using CSS background-image property

The first step to rendering an image with the CSS background image is creating an element with a defined width and height property. This element acts as a container for the image. The following code example illustrates how to achieve this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Using the CSS background images</title>
    <style>
      h1 {
        text-align: center;
        font-family: sans-serif;
      }

      .bg-img {
        background-image: url("https://images.unsplash.com/photo-1548614229-c1fe21dfab63?q=80&w=1080&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D");
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <h1>Displaying an image with the CSS <code>background-image</code></h1>
    <div class="bg-img"></div>
  </body>
</html>
A visual illustration of an image display via the CSS background image

Accessible background images

When displaying images that contain vital information for the end users, authors recommend using an HTML <img> tag with proper alt text instead of a CSS background image for accessibility reasons. However, if you must use a CSS background image for trivial photos, consider providing an alternative text to help screen readers understand the image content.

When providing an alternative text, authors recommend you avoid using a <div> tag with any content. Because setting a role=img and an aria-label on the <div> tag could obscure the content inside, or assistive technology might ignore the aria-label. Therefore, the authors advise developers to use an empty <span> and an aria-label with role=img. Consider the following codes when providing an alternative text for a CSS background image.

Do this:

<div>
  <span class="background-image" role="img" aria-label="[place alt text here]>  </span>
    [all the rest of my content]
</div>

Don’t do this:

<div class="background-image" role="img" aria-label="some text describing the image">
   [all the rest of my content]
</div>

Browser compatibility for CSS background image

CSS background properties are generally well-supported across modern browsers, and compatibility is not a significant concern. However, it’s vital to take note of specific considerations when working with outdated versions of Internet Explorer (IE). The following table shows browser support for the background image values:

ChromeEgdeFirefoxOperaSafari
background-image11213.51
Multiple backgrounds1123.610.51.3
SVG images81249.55
element()NoNo4 -x-NoNo
Gradients1123.5114
image-set()113113889914

CSS image styling techniques

When it comes to web design, knowing how to transform images with CSS into visually appealing elements is crucial to enhancing the user experience. CSS provides numerous options for styling graphics in a way that allows us to achieve the following:

  • create cool effects

  • create transparent images

  • align images

  • create responsive image

  • define image border radius etc.

Creating rounded images

We can style images to have rounded corners by defining the border-radius property. Adding a rounded corner to images makes them appear softer and visually appealing. Consider the following examples:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Rounded images</title>
    <style>
      div {
        text-align: center;
        padding-top: 2.5rem;
      }

      img {
        max-width: 100%;
        height: auto;
        border-radius: 16px;
      }
    </style>
  </head>
  <body>
    <div>
      <img
        alt="A calm body of water during golden hour"
        src="https://images.unsplash.com/photo-1548567117-02328f050eaa?q=80&w=480&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
        
      />
    </div>
  </body>
</html>
A visual illustration of setting a rounded corner on an image

Creating a circular image

Circular images can be achieved by combining equal values of the height and width property with a border-radius of either 50% or 999px. The code example below shows how to achieve circular images

img {
   width: 480px;
   height: 480px;
   border-radius: 50%;
}
A visual illustration of creating a circular image.

Aligning an image

We can align an image left, right, and center by defining the margin or text-align property. An image is left-aligned by default if the browser has a left-right orientation. The following code example shows how to center or right-align an image:

  • Right aligning an image

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Image alignment</title>
        <style>
          div {
            text-align: right;
            padding-top: 1.5rem;
          }
    
          img {
            width: 400px;
            height: 400px;
          }
        </style>
      </head>
      <body>
        <div class="img-container">
          <img
            alt="A calm body of water during golden hour"
            src="https://images.unsplash.com/photo-1548567117-02328f050eaa?q=80&w=480&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
    
          />
        </div>
      </body>
    </html>

    Right alignment with margin property

    div {
      padding-top: 1.5rem;
      width: 100%;
    }
    
    img {
      display: block;
      width: 400px;
      height: 400px;
      margin-left: auto;
    }
    A visual illustration of a right aligned image
  • Center aligning an image

    Centering an image with margin property

    div {
      padding-top: 1.5rem;
      width: 100%;
    }
    
    img {
      display: block;
      width: 400px;
      height: 400px;
      margin: 0 auto;
    }

    Centering an image with text-align property

    div {
      padding-top: 1.5rem;
      text-align: center;
    }
    
    img {
      width: 400px;
      height: 400px;
    }
    A visual illustration of a center aligned image

Explore additional methods for aligning your images by referring to the content in the following article: Aligning Content in CSS.

Creating a transparent image

Defining the opacity property allows us to control the transparency level of an image. An element has an opacity of 1 by default, whereas an opacity of 0 results in a completely invisible image. The example below creates a semi-transparent photo by setting the opacity to 0.5:

img {
  width: 400px;
  height: 400px;
  opacity: 0.5;
}
A visual illustration of a semi-transparent photo

Adding special effects to an image

Using the CSS image filter property, we can add unique visual effects to an element. This property allows creative manipulation of visual content to achieve specific artistic goals. You can also explore this amazing article on the filter property if you need more understanding. The syntax is as follows:

filter: <filter-function> [<filter-function>]* | none;

The commonly used filter functions include the following:

  • brightness(): Adjusts the overall lightness or darkness of an image.

  • contrast(): Modifies the sharpness of the image.

  • saturate(): Adjusts the intensity or vividness of colors in the image.

  • grayscale(): Applies different shades of gray to an image.

  • blur(): Blurs the image.

  • sepia(): Applies a monochrome effect to an image.

A visual illustration of the effect of the different filter functions.

Transforming an image

CSS allows us to apply transform effects like skew, rotate, scale, and translation to an image using the transform property. The following is an example of applying a transform effect:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Image transformation</title>
    <style>
      div {
        padding-top: 1.5rem;
        width: 100%;
        text-align: center;
      }

      img {
        width: 400px;
        height: 400px;
        transition: transform 0.3s ease-in-out;
      }

      img:hover {
        transform: rotate(360deg) scale(0.75) skew(30deg);
      }
    </style>
  </head>
  <body>
    <div class="img-container">
      <img
        src="https://images.unsplash.com/photo-1548567117-02328f050eaa?q=80&w=480&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
        alt="A calm body of water during golden hour"
      />
    </div>
  </body>
</html>

Responsive resizing of images

Image responsiveness is a process that will automatically resize images to fit the current device screen sizes. A max-width property is defined to achieve a responsive image. This property ensures the image does not exceed its original size but can still resize to fit the container.

img {
  max-width: 100%;
  height: auto;
}

Maintaining an image aspect ratio

So far, we have used specific widths and heights in some of the above examples, resulting in image distortion. By defining the object-fit property, we can control how the image fits in a specified dimension while maintaining its aspect ratio. The object-fit property accepts the following values:

  • fill: This value stretches the image to fill its container, potentially causing distortion.

  • contain: This value scales the image to fit its container without cropping, maintaining the aspect ratio but potentially leaving empty spaces.

  • cover: This value scales the image to cover its container while maintaining the aspect ratio. Some parts of the content end up clipped.

  • none: This value does not resize the image. If the image is large, it will scale down to fit the container, but the image will maintain its original size if it’s smaller.

The object-fit property syntax is as follows:

object-fit: fill | contain | cover | none | inherit;
A visual representation of applying the object-fit property

Best practices for CSS image styling

When working with CSS and images, there are several best practices to ensure optimal performance, user experience, and accessibility. These guidelines include the following:

  • Ensure images are accessible.

  • Use CSS background images sparingly.

  • Use images optimized for the web.

  • Ensure images are responsive.

Accessible images

Most images are crucial to the user flow on a web page. Providing an alternative text for your images ensures a website is accessible to all users, including the visually impaired. To learn more about this using alternative text, check the article on the rules of alt. Also, consider color contrast on all images for readability.

Use CSS background images sparingly

There are two ways to add images to a web page.

  • with the <img> HTML element.

  • with the background-image CSS property.

However, knowing when to use either is vital for accessibility, Search Engine Optimization (SEO), etc. Therefore, if possible, avoid using CSS background images for important informational images. Furthermore, when using CSS background for ambient images, provide alternate text as a courtesy. Consider placing the image in an empty <span> with an aria-label and role=img wrapped in a <div> with content.

Optimize images for the web

Multiple large images can impact performance. Therefore, it is essential to aim to use images that suit the design image dimension. If the provided image dimension exceeds the design requirement, use image edit tools to resize it before adding it to a web page. Avoid using CSS to resize large images; this puts pressure on the browser.

Ensure image responsiveness

If you display images on a website, ensure they are responsive and look good on various devices and screen sizes. Responsive images are crucial for SEO and enhancing user engagement.

Practical application of CSS image styling

The previous sections discussed techniques to style an image. This section will delve into a more practical approach, exploring strategies to elevate the aesthetics, responsiveness, and overall impact of an image on your website.

Achieving an image overlay effect

An image overlay effect involves placing a semi-transparent or colored layer on top of an image to achieve a specific visual result. This is particularly useful when the image has high contrast and you need to show some content. The following example uses the before pseudo-selector to achieve an overlay effect:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Image overlay</title>
    <style>
      div.img-container {
        margin-top: 1.5rem;
        width: 100%;
        text-align: center;
        position: relative;
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      div.img-container::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgb(0, 0, 0);
        opacity: 0.35;
        transition: opacity 0.3s ease-in;
      }

      .img-container:hover::before {
        opacity: 0.8;
      }

      .img-container img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
      }

      .img-container p {
        color: white;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 1.5rem;
        opacity: 0;
        transition: opacity 0.3s ease-in;
        position: relative;
        z-index: 1;
      }

      .img-container:hover > p {
        opacity: 1;
      }
    </style>
  </head>
  <body>
    <div class="img-container">
      <img
        alt="A snow covered mountains and trees during daytime"
        src="https://images.unsplash.com/photo-1547409594-d172436140a5?q=80&w=1080&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"

      />
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Repudiandae,
        esse nam magni blanditiis culpa consequuntur!
      </p>
    </div>
  </body>
</html>

Implementing an image gallery

Image galleries are a collection of images in a particular section of a webpage. CSS provides several methods to organize them in a visually appealing way that enables users to view and interact with them effortlessly. The example below uses a CSS grid to achieve a responsive image gallery:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Image galleries</title>
    <style>
      div.img-gallery {
        margin-top: 1.5rem;
        width: 100%;
        text-align: center;
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
      }

      img {
        max-width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div class="img-gallery">
      <div>
        <img
          src="https://images.unsplash.com/photo-1548567117-02328f050eaa?q=80&w=1080&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="A calm body of water during golden hour"
        />
      </div>
      <div>
        <img
          src="https://images.unsplash.com/photo-1547409594-d172436140a5?q=80&w=1931&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="A snow covered mountains and trees during daytime"
        />
      </div>
      <div>
        <img
          src="https://images.unsplash.com/photo-1546527706-59aa9718a426?q=80&w=2071&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="A trees during golden hour"
        />
      </div>
      <div>
        <img
          src="https://images.unsplash.com/photo-1548506923-99f6e89852fe?q=80&w=2074&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="A waterfalls under white skies"
        />
      </div>
      <div>
        <img
          src="https://plus.unsplash.com/premium_photo-1667200898705-742de3bd555a?q=80&w=1974&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="An aerial view of a body of water surrounde -by rocks"
        />
      </div>
      <div>
        <img
          src="https://images.unsplash.com/photo-1523712999610-f77fbcfc3843?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
          alt="A calm forest heat-by sunbeam"
        />
      </div>
    </div>
  </body>
</html>

Explore the tutorial video below to learn other creative ways to implement an image gallery:

Final notes

Styling images with CSS for aesthetics and efficacy enhances your web pages’ visual appeal, interactivity, and user experience. While styling images with CSS, always be mindful of accessibility, responsiveness, and performance.

Frequently, developers rely on CSS to handle tasks like resizing large images with broad dimensions and improving the clarity of poorly defined images. However, this approach can have repercussions on performance and page loading speed. By implementing the insights gained from this article, developers can display images with better quality and resolution. They can also ensure accessibility without compromising aesthetics and channel their creativity toward crafting visually engaging content.

In addition, if you are more interested in enhancing the aesthetics of your web development projects without manually crafting the UI components. Visit purecodes.ai and explore our library of CSS3 components.

Ofili Chukwuemeka Timothy

Ofili Chukwuemeka Timothy