Basic usage of the image tag (img)
Basic Usage of the Image Tag (img)
The <img>
tag is the core element in HTML for embedding images on web pages. It does not require a closing tag and is an empty element. Images can be in formats such as JPEG, PNG, GIF, or SVG, and the image source is specified via the src
attribute.
Basic Syntax and Attributes
The most basic image tag requires only the src
and alt
attributes:
<img src="example.jpg" alt="Example image">
Common attributes include:
src
: Specifies the image URL (required)alt
: Alternative text (strongly recommended)width
/height
: Sets display dimensionsloading
: Controls lazy loading behaviordecoding
: Controls decoding method
Detailed Usage of the src Attribute
The src
attribute supports multiple path formats:
<!-- Relative path -->
<img src="../images/logo.png" alt="Company logo">
<!-- Absolute path -->
<img src="/assets/photos/profile.jpg" alt="Profile picture">
<!-- Full URL -->
<img src="https://example.com/pic.jpg" alt="Web image">
<!-- Base64-encoded image -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." alt="Inline image">
Importance of the alt Attribute
The alt
attribute is not only helpful for SEO but also critical for accessibility:
<!-- Descriptive text -->
<img src="chart.png" alt="2023 Quarterly Sales Trend Chart: Q1 growth 15%, Q2 growth 22%">
<!-- Decorative image -->
<img src="divider.png" alt="">
<!-- Image with link -->
<a href="product.html">
<img src="product-thumbnail.jpg" alt="New Smartphone - Click for details">
</a>
Dimension Control
It is recommended to specify both width
and height
to avoid layout shifts:
<!-- Fixed dimensions -->
<img src="photo.jpg" width="800" height="600" alt="Scenic photo">
<!-- Responsive design (with CSS) -->
<style>
.responsive-img {
max-width: 100%;
height: auto;
}
</style>
<img src="large-image.jpg" class="responsive-img" alt="Responsive image">
Advanced Usage
srcset and sizes Attributes
Implement responsive image loading:
<img src="small.jpg"
srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, (max-width: 1000px) 768px, 1200px"
alt="Responsive image example">
Lazy Loading
Optimize page loading performance:
<img src="placeholder.jpg"
data-src="actual-image.jpg"
loading="lazy"
alt="Lazy-loaded image"
class="lazyload">
Image Mapping
Create clickable areas:
<img src="worldmap.jpg" alt="World map" usemap="#worldmap">
<map name="worldmap">
<area shape="rect" coords="34,44,270,350" href="europe.html" alt="Europe">
<area shape="circle" coords="337,300,44" href="australia.html" alt="Australia">
</map>
Performance Optimization Tips
-
Choose the appropriate image format:
- Photos: JPEG
- Icons/simple graphics: PNG
- Animations: GIF
- Vector graphics: SVG
-
Use modern formats:
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Fallback image">
</picture>
- Preload critical images:
<link rel="preload" href="hero-image.jpg" as="image">
Common Problem Solutions
Image Loading Failure
Use the onerror
event for fallback solutions:
<img src="primary.jpg"
onerror="this.src='fallback.jpg';this.alt='Image failed to load'"
alt="Primary image">
Centering Images
Multiple CSS implementation methods:
<style>
.center-img {
display: block;
margin: 0 auto;
}
.flex-center {
display: flex;
justify-content: center;
}
</style>
<!-- Method 1 -->
<img src="logo.png" class="center-img" alt="Centered logo">
<!-- Method 2 -->
<div class="flex-center">
<img src="banner.jpg" alt="Banner ad">
</div>
Image Filter Effects
Add visual effects via CSS:
<style>
.filtered-image {
filter: grayscale(50%) brightness(110%);
transition: filter 0.3s;
}
.filtered-image:hover {
filter: none;
}
</style>
<img src="portrait.jpg" class="filtered-image" alt="Portrait with filter">
Practical Application Examples
Product Display Gallery
<div class="product-gallery">
<img src="product-1.jpg"
alt="Blue T-shirt front"
data-fullsize="product-1-large.jpg"
class="thumbnail">
<img src="product-2.jpg"
alt="Blue T-shirt back"
data-fullsize="product-2-large.jpg"
class="thumbnail">
<img src="product-3.jpg"
alt="Blue T-shirt detail"
data-fullsize="product-3-large.jpg"
class="thumbnail">
</div>
<script>
document.querySelectorAll('.thumbnail').forEach(img => {
img.addEventListener('click', () => {
const fullsize = img.getAttribute('data-fullsize');
window.open(fullsize, '_blank');
});
});
</script>
User Avatar Handling
<div class="avatar-container">
<img src="user-avatar.jpg"
alt="User avatar"
width="150"
height="150"
class="avatar"
onerror="this.src='default-avatar.png'">
</div>
<style>
.avatar {
border-radius: 50%;
object-fit: cover;
border: 3px solid #fff;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>
Browser Compatibility Notes
- PNG transparency issues in older IE versions:
<!--[if lt IE 7]>
<style type="text/css">
img { behavior: url(iepngfix.htc); }
</style>
<![endif]-->
- Image format support detection:
function checkWebPSupport(callback) {
const img = new Image();
img.onload = function() {
callback(img.width > 0 && img.height > 0);
};
img.onerror = function() {
callback(false);
};
img.src = 'data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==';
}
Security Best Practices
- Prevent image hotlinking:
<!-- Set in .htaccess -->
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
- Content Security Policy:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' data: https://trusted.cdn.com">
- Prevent image injection:
// Server-side handling of uploaded images example
$allowed_types = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['image']['type'], $allowed_types)) {
die('Invalid file type');
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:图像映射的使用
下一篇:图像的替代文本(alt属性)