文
章
目
录
章
目
录
响应式网页设计
响应式网页设计用于使您的网页在所有设备上(电脑、平板、智能手机等)都看起来适当、好看和布局良好。
响应式网页设计使用HTML和CSS来调整、隐藏、缩小、放大或移动内容。它使内容在任何屏幕上都看起来不错。
响应式图像
可以按比例缩放以适应任何浏览器大小的图像称为响应式图像。
如何使图像响应式?
通过使用宽度属性
将CSS宽度属性设置为100%,使图像具有响应性并可以缩放上下。
示例
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Responsive Image</h2>
<p>When we set the CSS width property to 100%, it makes the image responsive.
Resize the browser window to see the effect.</p>
<img src="img_girl.jpg" style="width:100%;">( change image)
</body>
</html>
注意:上述方法(宽度:100%)的问题是图像可以被放大到大于其原始大小。因此,最好使用max-width属性。
通过使用max-width属性
这种方法是最佳且最常用的,因为它确保图像在需要时会缩小,但不会放大到大于其原始大小。
示例
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Responsive Image</h2>
<p>"max-width:100%" makes the image responsive and also ensures that the image
doesn't get bigger than its original size.</p>
<p>Resize the browser window to see the effect.</p>
<img src="img_girl.jpg" style="max-width:100%;height:auto;"> (Change the image)
</body>
</html>
根据浏览器宽度更改图像
通过使用HTML的<picture>元素,您可以根据浏览器宽度设置两个或更多的图像。当您更改浏览器大小时,它将更改图像,例如,电脑和手机。
示例
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Change Images Depending on Browser Width</h2>
<p>Resize the browser width and the image will change at 600px and 1500px.</p>
<picture>
<source srcset="img_smallflower.jpg" media="(max-width: 600px)">(Change image)
<source srcset="img_flowers.jpg" media="(max-width: 1500px)">(Change image)
<source srcset="flowers.jpg">
<img src="img_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
</body>
</html>
响应式文本大小
我们可以使用“vw”单位(视口宽度)使文本大小具有响应性。通过使用这种方法,我们可以使文本大小跟随浏览器窗口屏幕。
示例
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h1 style="font-size:10vw;">Here size is 10vw.</h1>
<p style="font-size:6vw;">Here size is 6vw.</p>
<p style="font-size:4vw;">Here size is 4vw.</p>
<p>Resize the browser window to see how the text size changes.</p>
</body>
</html>
注意:视口指定浏览器窗口大小。1vw = 视口宽度的1%。也就是说,如果视口宽度为100厘米,1vw就是1.0厘米。
媒体查询
我们还可以使用媒体查询来创建响应式网站。