Adding Images in CSS

We search the web for engaging and informative content, frequently discovering it in plain text format. HTML provides techniques to improve this basic text by incorporating multimedia elements such as images, audio clips, and videos, as well as embedding external content through inline frames from other websites.

Websites have consistently allowed for the inclusion of images, audio files, videos, and inline frames. While inline frames and images have generally received good browser backing, the process of adding videos and audio to a website has historically been somewhat challenging. Fortunately, this process has now been enhanced and made more straightforward with direct HTML support.

These days, we can make use of images, audio files, videos, and inline frames without limitations as they are compatible with a wide range of popular browsers.

Adding Images

Images are inserted into a webpage using the inline element. This element remains devoid of any content within it, standing alone as a single tag. To enable the element to work properly, a src property with a corresponding value specifying the image's source is essential. Typically, the value of the src property is a URL directing to the server hosting the website.

The alt attribute, responsible for providing alternative text describing the content of an image, needs to be paired with the src attribute. Search engines and assistive tools rely on the alt attribute to convey the significance of an image. If the image is not accessible, the alt text will be displayed instead.

The absent image has been substituted with the alternate text, "A dog with black, brown, and white fur adorned with a kerchief."

Accepted Picture Formats

There are multiple file formats available for images, and different web browsers may have varying levels of support for these formats. The most commonly accepted formats for online use are GIF, JPG, and PNG. Currently, JPG and PNG are the most popular file types. To optimize loading speed, JPEG format is preferred as it provides high-quality images with rich color palettes while maintaining a reasonable file size. PNG format is suitable for images with low color depths or transparent backgrounds. Typically, JPG files are used for photographs, while PNG files are more commonly used for icons and background designs.

Sizing Images

The dimensions of an image are significant as they inform the browser about the appropriate size of the image even prior to loading the webpage, enabling the browser to allocate space and display the page more efficiently. Various methods can be employed to adjust the size of images to ensure they align correctly on a website. One approach involves utilizing the width and height attributes within the HTML element.

CSS's width and height properties can also resize images. These CSS attributes take precedence over HTML attributes when both are employed together.

When a single dimension is defined, the other dimension will adjust automatically to maintain the image's aspect ratio. For example, if we specify the height of an image as 200 pixels, the width will adjust accordingly to keep the image at 200 pixels tall without much concern for its width. Modifying both the width and height of an image is possible but may distort the image's aspect ratio.

While determining the initial dimensions of an image using the width and height attributes in HTML provides semantic significance, handling multiple images that require uniform sizing can pose difficulties. In such scenarios, the common practice involves adjusting the images' dimensions using CSS.

Positioning Images

There are various techniques available for organizing images on a webpage. Initially, images are displayed as inline-level elements, but you have the flexibility to manipulate their positions using CSS. In particular, you have the option to utilize the float, display, and box model attributes such as padding, border, and margin to alter the placements of your images.

Inline Positioning Images

The element is initially set as an inline-level element. If an image is inserted into a webpage without any customized styles, it will align horizontally with the nearby content. This alignment may cause noticeable vertical spaces within the line if the image height affects the line height adjustment.

Gatsby, a puppy of mixed breed, displays a stunning combination of black, brown, and white fur. He delights in receiving belly rubs and expressing his disapproval loudly at passing fire engines. Although he spends a significant portion of his day napping, he is quick to chase after any birds that happen to venture into his vicinity.

Images for Block Positioning

When an image is assigned the display property with a block value, it automatically transforms into a block-level element. Consequently, this enables the content around it to be aligned both above and below the image, ensuring it stays on its designated line.

Syntax:

Example

img { 
display: block; 
}

This section is labelled "teaser col-1-3"> <h5>Speakers</h5> <a href="speakers.html"> <img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Professional Speaker"> <h3>Top-Rated Speakers</h3> </a> <p>More than twenty amazing speakers are joining us from all around the world to tell their tales.<p> </section>

Positioning Images Flush Left or Right

Displaying an image as an inline-block or even an inline-block may not always be the preferred choice. The image can be aligned to the left or right of the content it is within, allowing other content to wrap around it accordingly. This can be achieved by using the float property with either a left or right value.

The float property was initially created to align images either to the left or right side of a parent element, as discussed in Lesson 5 on "Positioning Elements." We will now apply it for its original functionality.

A standalone image is a good starting point, with other elements aligning next to it. We can make use of the margin property to create space around the image. Additionally, if needed, we can design an image container by utilizing the padding, border, and background properties.

Example

// CSS
img { 
float: right; 
margin: 8px 0 0 20px; 
padding: 4px; 
background: #eaeaed; 
border: 1px solid #9799a7;
}

When to Use a Background Image vs Image Element

  • A web page can have pictures added using two main methods. One method is to utilise the element inside the HTML discussed here. An alternative method for adding a background picture to an element in CSS is to use the background or background-image property. Both options are functional, but they each have certain applications.
  • When a picture has semantic significance, and its content is pertinent to the page's content, using the element within HTML is the better choice.
  • When the picture is integrated into the page's design or user experience, the recommended choice is to utilise the background or background-image property in CSS. As a result, it has no direct bearing on the page's content.
  • The element is widely used, and its addition to the HTML standard forever altered the foundation of website development.
  • In Practice

Let's examine our Styles Conference website to identify areas where we can incorporate several photographs now that we have learned how to insert and organize images within a webpage.

Let's begin by improving our homepage with some images. Specifically, we'll add a picture promoting a couple of our pages within each teaser section.

But before we proceed, we should create a fresh directory named "images" within the existing "assets" folder. Following that, we will establish a new directory named "home" within the "images" directory, specifically designated for images related to our home page. Within the "home" directory, three files will be included: speakers.jpg, schedule.jpg, and venue.jpg. (You can obtain these images by downloading the provided zip file for reference.)

Then, each teaser section within our index.html file contains a <figure> element wrapping an <img> element. We should move the <figure> element before the <img> element and introduce a fresh <figcaption> element in its position. All <img> elements will include an alt attribute with a descriptive value for each image, while the src attribute value will align with the designated folder structure and filename.

This section is labelled "teaser col-1-3"> <h5>Speakers</h5> <a href="speakers.html"> <img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Professional Speaker"> <h3>Top-Rated Speakers</h3> </a> <p>More than twenty amazing speakers are joining us from all around the world to tell their tales.<p> </section>

After incorporating several images onto our homepage, it is essential to verify that they align with the overall page design and refine their appearance.

Let's transform the images within the teaser sections into block-level elements, considering that they are initially inline-level elements. It is important to specify a maximum width of 100% for these images to prevent them from exceeding the width of their respective columns. Modifying this width value is essential for allowing the images to adjust and fit within the columns' widths effectively.

To provide some space around the images, we can round the corners slightly and include a bottom margin of 22 pixels.

When integrating these fresh styles into our existing homepage styles, our CSS code will resemble this, using the teaser class as a qualifying selector for the elements:

Syntax:

Example

.teaser img {
max-width: 100%; 
margin-bottom: 22 px; 
display: block; 
border-radius: 5 px
}

Audio Fallbacks & Multiple Sources

Presently, the top three prevalent audio formats are recognized by various web browsers: OGG, MP3, and WAV. It will be necessary to utilize several audio fallback options within the start and end tags of an audio element to ensure the best possible compatibility with different browsers.

First, we will take the src property out of the <audio> element. Instead, we'll use the <source> element inside the <audio> element with a src attribute to specify a new source.

Each type of audio file can be sequentially displayed using an \<audio> element and src attribute. The type property will be employed to aid the browser in quickly identifying the available audio formats. Upon recognizing the format, the browser will load the audio file and disregard all others.

All browsers might not support the <audio> element because it was first introduced in HTML5. We may offer a link to download the audio file after any <source> elements inside the <audio> element.

Example

<audio controls>
  <source src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" type="audio/ogg">
  <source src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" type="audio/mpeg">
  <source src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" type="audio/wav">
  Please <a href="jazz.mp3" download>download</a> the audio file.
</audio>

To guarantee that the audio player is visible in browsers that support the element, the controls Boolean property is included in the <audio> element of the preceding code. Instead of having a src property, the <audio> element encapsulates three distinct <source> components. Every <source> element has two attributes: a type property that indicates the kind of audio file and a src attribute thaC# Tutorials to a different audio file format. If a browser cannot detect any audio file type, the anchor link for downloading the element will be shown as a last resort.

The introduction of the <video> element into HTML5 coincided with the addition of the <audio> element, which bears a striking resemblance.

Adding Video

In HTML5, the process of including audio and video is quite similar. Instead of employing the <audio> element, we make use of the <video> element. The identical fallbacks and attributes (such as source, autoplay, controls, loop, and preload) are equally valid.

If the controls Boolean attribute is not specified, the <audio> element audio clip will be hidden. Videos, on the other hand, will be displayed when the control's Boolean attribute is not set. However, it may be difficult for users to view the content unless the autoplay Boolean functionality is enabled. In most cases, it is recommended to include the controls Boolean attribute unless there is a specific need to restrict users from controlling playback options such as starting, pausing, or replaying the video.

Specifying the dimensions of videos is essential as they occupy space on the webpage. The width and height properties in CSS are commonly employed for this purpose. This practice facilitates better management of video size within the designated page layout. Similar to images, defining dimensions helps browsers render videos efficiently and allocate the necessary space for displaying the video content.

Example

<video src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" controls>
</video

Including a video demonstration

This video demonstration is hosted on a local server for quicker loading times; however, you are still able to analyze and modify the code within CodePen.

Customizing Audio & Video Controls

By default, each browser defines the playback and volume element settings. Customization options for the media player's look and behavior may vary based on the website's design. If customization is desired, a tailored player can be developed with the help of JavaScript for functionality.

Additionally, the alt attribute value should specify that the image serves as a control and requires the necessary interaction to operate properly when a customized player uses the <img> element as a control.

Poster Attribute

The poster property is an additional attribute that can be assigned to the <video> element. By using the poster functionality, we can specify an image (in the form of a URL) that will be displayed prior to the beginning of a video. In the given illustration, the poster for the Earth video is a screenshot extracted from the video itself.

Example

<video>
src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" controls poster="earth-video-screenshot.jpg"
</video>

Video Fallbacks

Video fallbacks are also required, like the <audio> element. Within the <video> element, the same markup syntax is used, with several <source> components for each type of file and a fallback to plain text.

Example

<video controls>
  <source src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" type="video/ogg">
  <source src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" type="video/mp4">
  Please <a href="earth.mp4" download>download</a> the video.
</video>

Using an embedded video from Vimeo or YouTube serves as an additional fallback solution that can be employed in place of a basic text fallback. These platforms where videos are hosted enable users to upload their content, provide a standard video player, and utilize an inline frame to integrate the videos into a webpage.

HTML5 Audio & Video File Formats

The file extensions required for the <audio> and <video> modules differ, just like the level of browser compatibility for these features. Each web browser has its preferred file type for audio and video content.

A quick search will reveal numerous options. Some tools are available to help convert an audio or video file into various formats.

Adding Inline Frames

Embedding another HTML page inside the current page is another method of adding content to a webpage. An inline frame, or <iframe> element, is used for this. The content from the embedded HTML page is shown on the current page when the <iframe> element accepts the URL of another HTML page in the src property value. The value of the src property can be either an absolute URL for a completely external page or a relative URL to the page on which the <iframe> element appears.

Many websites integrate content from external sources such as YouTube and Google Maps by utilizing the <iframe> element.

Example

<iframe src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"></iframe

Input Required

This code uses input(). Please provide values below: