Chapter 9: Working with Images and Media
Images and media can bring a website to life, enhancing user experience and engagement. CSS provides various properties to control the display and layout of images, videos, and other media elements on a webpage. In this chapter, we’ll cover essential techniques for working with media, including responsive images and embedded videos.
Adding and Styling Images
You can use the <img>
tag to add images to your webpage. CSS then allows you to style and control their size, borders, and alignment.
<img src="image.jpg" alt="Description of image" class="styled-image">
/* Basic styling for images */
.styled-image {
width: 100%; /* Makes image responsive */
max-width: 600px; /* Limits the max size */
border-radius: 8px; /* Adds rounded corners */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Adds a shadow effect */
}
Responsive Images with CSS
Making images responsive ensures they scale to fit the screen size. The simplest way to achieve this is by setting the width to 100% and controlling the maximum size.
/* Responsive image */
.responsive-image {
width: 100%;
height: auto; /* Maintains aspect ratio */
max-width: 800px; /* Optional max width */
}
Embedding and Styling Videos
Videos can be embedded using the <video>
tag or by embedding content from video-sharing platforms like YouTube. CSS allows you to control the size and appearance of embedded videos.
<video controls class="styled-video">
<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
/* Styling for videos */
.styled-video {
width: 100%; /* Makes video responsive */
max-width: 800px; /* Limits max size */
border-radius: 8px; /* Adds rounded corners */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Adds a shadow effect */
}
Example: Embedding a YouTube Video Responsively
To embed a responsive YouTube video, wrap the iframe in a container with a fixed aspect ratio using padding. This ensures the video scales properly on different screen sizes.
<div class="video-container">
<iframe src="https://www.youtube.com/embed/example" frameborder="0" allowfullscreen></iframe>
</div>
/* Responsive YouTube video */
.video-container {
position: relative;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
height: 0;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Experimenting with Media
Now that you know how to add and style images and videos, try experimenting with different layouts, sizes, and styles. Media elements can add great value to your website when used thoughtfully and responsively.