Images are a crucial part of any web page, enhancing the visual appeal and providing essential information to users. In this tutorial, we will explore how to embed images in HTML and style them using CSS. By the end of this section, you'll be able to add and customize images on your web pages effectively.
HTML provides a simple way to include images using the <img> tag. This tag allows you to specify the source of the image and other attributes like alt text, which is important for accessibility. CSS can then be used to style these images, such as setting dimensions, adding borders, or applying transformations.
To embed an image in HTML, use the <img> tag with the src attribute pointing to the image file and the alt attribute providing alternative text.
1<img src="path/to/image.jpg" alt="Description of the image">
Once you have your images embedded, you can style them using CSS. Here are some common properties you might use:
1img {2width: 300px;3height: auto;4border: 2px solid #ccc;5border-radius: 10px;6box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);7}
Let's create a simple HTML page that includes an image styled with CSS.
1<!DOCTYPE html>2<html lang="en">3<head>4<meta charset="UTF-8">5<meta name="viewport" content="width=device-width, initial-scale=1.0">6<title>Styled Image</title>7<style>8img {9width: 300px;10height: auto;11border: 2px solid #ccc;12border-radius: 10px;13box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);14}15</style>16</head>17<body>18<h1>My Favorite Image</h1>19<img src="https://example.com/my-image.jpg" alt="A beautiful landscape">20</body>21</html>
To ensure images are responsive and scale well on different devices, you can use CSS to set the width to a percentage.
1img {2width: 100%;3height: auto;4}
This will make the image take up the full width of its container while maintaining its aspect ratio.
You can also add interactive effects using CSS. For example, changing the border color on hover.
1img {2transition: border-color 0.3s ease;3}45img:hover {6border-color: #007BFF;7}
In the next section, we will explore CSS transitions, which allow you to animate changes in CSS properties over time. This will enable you to create smooth and engaging user experiences on your web pages.
Stay tuned for more tutorials and happy coding!