1. Home
css

CSS Tutorial: A Comprehensive Guide

Master CSSS with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and upskill yourself.

  • 23
  • 4
right-top-arrow
8

CSS Images

Updated on 18/09/2024347 Views

Imagine a website without visual elements. It sometimes may leave a user with an impression of being overwhelmed. CSS Images help you to add visual content, such as photographs, illustrations, and icons, to your web pages using Cascading Style Sheets (CSS) language. CSS is a language that is meant to style and layout web pages. CSS images mean the way images are embedded and altered using CSS code.

The Importance of Images in Web Design

Visual elements are a key factor in creating a successful web layout. Strategic use of images can significantly enhance the following:

  • Visual Appeal: Good, well-chosen pictures that are used to break long texts make the website look more attractive and interesting.
  • Storytelling: CSS images are an effective way of portraying emotions as well as communicating difficult ideas. A good picture has the potential to narrate a story, representing your unique brand personality, and making a long-lasting impact on your visitors.
  • User Experience: Imagery can aid users in navigating through your website, pinpointing crucial information, and making it easier for them to understand.

Essential CSS Image Properties

CSS is a tool that helps you to define how an image is going to appear on your website. By varying image properties, you can create different designs from a simple layout to a complex visual. Let's now dwell on some basic CSS image properties.

Display

The display property is the one that determines if an image is an in-line or a block element. Here are the most common display values for CSS images and their use cases:

Inline

A picture inline acts exactly like text, and it is aligned with the surrounding text on the same line. This is used for tiny images, or icons, that are placed inside a sentence.

HTML

<p>This is a sentence with an image of an apple embedded within the text <img src="apple.png" alt="An apple"></p>

Block

The block-level image behaves like a standalone block element, starting on the next line and occupying the entire available width. This is perfect for inserting images into your content that are embedded in a standalone manner.

HTML

<img src="mountain.jpg" alt="A Mountain range">

Inline-Block

This is an inline and block behavior blended. A picture in an inline-block is on the same line as text but does not stretch more than its width; therefore, text can wrap around it. This is particularly useful when you want to have some text flow alongside images that are within paragraphs.

HTML

<p>This text wraps around the image (<img src="cat.jpg" alt="A cat"></p>

Inline vs. Block vs. Inline-Block

The following table describes the main differences between inline, block, and inline-block elements in CSS:

Parameter

Inline

Block

Inline-Block

Element Type

Sit on the same line with the adjacent content.

Start a new line, forcing a line break before and after the element.

Act like inline elements that sit on the same line as surrounding content.

Behavior

Cannot be styled with CSS using width or height properties.

The length and width of the border can be specified in CSS.

These can have their width and height set using CSS just like block elements do.

Example

spans, a (anchor tags).

div (division), h1 (heading), p (paragraph).

img (images), button.

Replacement

The image covers the whole area of its parent element and inherits the size of the parent element. This is particularly helpful for inserting logos or social media icons. For example,

HTML

<a href="#">

<img src="logo.png" alt="Company Logo">

</a>

None

This completely blank space will not be viewed, but the space it occupies on the page layout will remain. This can be used for temporary image removal or to adjust/adapt design to different screen sizes.

HTML

/* Initially display the image */

.my-image {

display: block;

}

/* Image hiding on small screens */

@media only screen and (max-width: (768px) {

.my-image {

display: none;

}

}

Width and Height

The width and height attributes define the CSS image size in pixels (px) or other relative units like percentages (%). The aspect ratio or the ratio between the image width and height is a critical factor that should be considered.

Maintaining Aspect Ratio

The aspect ratio is the original ratio of the image, which means it shouldn't appear distorted. An easy way to do this is by using the width or height property and the max-width or max-height property to restrict the other dimensions proportionally.

HTML

img {

width: 300px;

max-height: 200px;

}

Contain and Cover

These features are important for the display of images within a container element. Have an inbuilt feature of scaling that downsizes the image without distorting the aspect ratio, hence leaving the image well-contained with some empty spaces around it.

HTML

.image-container {

width: 400px;

height: 300px;

}

img {

width: 100%; /* occupies container width */

contain: strict;

}

Inversely, “cover” scales the image to fit the container completely; it therefore can cut off the image if it is necessary to maintain the aspect ratio.

HTML

.image-container {

width: 400px;

height: 300px;

}

img {

width: 100%; /* Container width */

cover: fill;

}

Positioning

CSS offers various positioning properties to control an image’s location within the document:

Static (Default)

An image stays in that position where it is included in the document flow.

Relative

The picture is fixed in its present position but can move relative to its normal position with the help of properties like top, right, bottom, and left.

HTML

img {

position: relative;

top: 20px;

right: 50px;

}

Absolute

This image is not part of the normal document layout anymore but is placed based on the containing element or the viewport, i.e. the entire browser window, using properties such as top, right, bottom, and left.

HTML

.container {

position: relative; /* Set the container as a relative element for absolute positioning */

width: 500px;

height: 300px;

}

img {

position: absolute;

top: 100px;

left: 150px;

}

Fixed

The image is anchored to a specific place in the viewport and remains in that position irrespective of the scrolling.

HTML

img {

position: fixed;

top: 0;

right: 0;

width: 100px;

height: 100px;

}

Background Images

The background images that you will use to give an additional appeal to your web page are one of the most potent means of design. Here’s how to leverage them effectively:

Setting Background Images

The background-image property should be used to provide the address of an image file you want to use as a background.

HTML

.section {

background-image: url("background.jpg");

}

Background Positioning

The background-position property will be used to control the positioning of the background image within its container. You can use keywords such as ‘top’, ‘center’, and ‘bottom’ to position an element, or you can use pixel value for more precise placement.

HTML

.section {

background-image: url("banner.jpg");

background-position: top left;

}

Background Repeat

The background-repeat property defines if the background image will be repeated within the container (and how). Some of the options are repeated (tiles the picture), repeat-x (repeats horizontally), repeat-y (repeats vertically), and no-repeat (shows the picture only once).

HTML

.wrapper {

background-image: url("pattern.png");

background-repeat: repeat;

}

Background Attachment

The background-attachment property is used to decide if the background picture scrolls together with the content or remains fixed. The background image will scroll down with the content by default. By contrast, fixing will prevent the background image from moving as the content is scrolled. This is helpful when it comes to the creation of parallax effects.

HTML

.header {

background-image: url("sky.jpg");

background-attachment: fixed;

}

Borders and Margins

Borders and margins are like visual separators and definitions that contribute to the overall look of your photos. Here's how to add CSS style for image borders and margins:

Borders

The border property gives the details of the style, width, and color of the image’s border. You have an option of setting the properties of individual borders for each side (top, right, bottom, left) or using the shorthand property to set them all at once.

HTML

img {

border: 5px solid red;

}

Margins

The margin property sets the margin of the image that is outside its border. For instance, borders may be set differently for each of the sides or with the shorthand property.

HTML

img {

margin: 10px 20px; /* 10px top & bottom, 20px left & right */

}

By intelligently using borders and margins along with other elements, you can define the uniqueness of the webpage.

Opacity and Visibility: Being in the Spotlight

CSS allows you to control how visible your images are:

Opacity

The opacity property dictates the transparency level of the image. A value of one means full opacity and zero means complete transparency.

HTML

.image-overlay {

opacity: 0.5; /* 50% opacity */

}

Visibility

The visibility property controls whether an image is to be visible or hidden. Use visible to show the picture, hidden to hide it, but keep the space it uses in the layout, and collapse to hide the image and take out the space it uses from the layout.

HTML

.product-image {

visibility: hidden; /* Initially hidden */

}

.product-image:hover {

visibility: visible; /* Visually on hover */

}

Recap

The functionality of CCS images allows you to exercise an enormous degree of control over the behavior and appearance of images on your website. This gives a lot of opportunities to use visual effects and design, and not just insert an image into your HTML. Remember, the main principle of CSS learning is constant practice and hands-on exploration. And now, get your preferred code editor, show your creativity, and shape stunning web pages by using CSS and images.

FAQs

1. How to insert an image in CSS?

Here’s an example for inserting an image:

CSS

.element {

background-image: url('image.jpg');

}

Replace ‘image.jpg’ with the path to your image file.

2. How to use CSS image set?

CSS feature ‘image-set’ enables you to provide images of different resolutions and formats.

CSS

.element {

background-image: image-set(

url('image.jpg') 1x,

url('image@2x.jpg') 2x

);

}

This will load image.jpg for standard displays and image@2x.jpg for high-resolution displays.

3. How do I style a particular image in CSS?

To style a specific image, you can use its class or ID selector along with CSS properties like ‘width’, ‘height’, ‘margin’, etc. For example:

CSS

.image-class {

width: 200px;

height: 200px;

margin: 10px;

}

4. How to place two images in CSS?

You can apply CSS to the display of multiple images by using them as background images for different elements or use several elements for that. For example:

HTML

<div class="image1"></div>

<div class="image2"></div>

CSS

.image1 {

background-image: url('image1.jpg');

}

.image2 {

background-image: url('image2.jpg');

}

5. Where can I find CSS images?

You can use the CSS images found at free or paid stock photo websites like Unsplash, Shutterstock, or Pixabay. Or you can design your images by using graphic design tools like Adobe Photoshop or Canva.

6. How to add a logo in CSS?

One way of inserting a logo via CSS is by using the ‘background-image’ property or by embedding it as an ‘<img>’ element within your HTML and styling it using CSS.

7. Can you edit an image in CSS?

No, CSS is not for editing images, but it is for style and layout. For this task, you would commonly use image editing software like Adobe Photoshop or GIMP.

image

Mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...