如何使用HTML和CSS创建响应式图片网格?
网页上的图片网格以网格形式显示图片。在一个外部网格中,我们可以创建内部网格。此外,需要为不同设备的图片网格设置响应式布局。在网页浏览器上,通过调整浏览器大小来检查响应式布局。让我们看看如何使用HTML和CSS创建一个响应式图片网格。
设置外部和内部网格
设置一个用于外部网格的div。在其中,设置内部网格。我们在外部网格内设置了三个内部网格。
<div class="outer-grid">
<div class="inner-grid">
<!—images -->
</div>
<div class="inner-grid">
<!—images -->
</div>
<div class="inner-grid">
<!—images -->
</div>
</div>
定位外部网格
使用`**display**`属性将外部网格设置为flex布局。`**flex-wrap**`属性设置为`**wrap**`值,以指定flex项目在必要时会换行。
.outer-grid {
display: flex;
flex-wrap: wrap;
padding: 0 4px;
}
定位内部网格
为内部网格设置flex布局。`flex-basis`设置为25%,因此`**flex: 25%**`。它设置flex项目的初始主要大小。`**max-width**`属性用于设置最大宽度。
.inner-grid {
flex: 25%;
max-width: 25%;
padding: 0 4px;
}
内部网格中的图片
内部网格中图片的宽度设置为100%。
.inner-grid img {
margin-top: 8px;
width: 100%;
padding: 10px;
}
设置响应式布局
当网页浏览器设置为小于800px时,响应式布局生效。`**flex**`属性设置为50%。
@media screen and (max-width: 800px) {
.inner-grid {
flex: 50%;
max-width: 50%;
}
}
当网页浏览器大小小于600px时,`flex`和最大宽度设置为100%。
@media screen and (max-width: 600px) {
.inner-grid {
flex: 100%;
max-width: 100%;
}
}
示例
以下是使用HTML和CSS创建响应式图片网格的代码:
<!DOCTYPE html>
<html>
<style>
* {
box-sizing: border-box;
}
h1 {
text-align: center;
}
.outer-grid {
display: flex;
flex-wrap: wrap;
padding: 0 4px;
}
.inner-grid {
flex: 25%;
max-width: 25%;
padding: 0 4px;
}
.inner-grid img {
margin-top: 8px;
width: 100%;
padding: 10px;
}
@media screen and (max-width: 800px) {
.inner-grid {
flex: 50%;
max-width: 50%;
}
}
@media screen and (max-width: 600px) {
.inner-grid {
flex: 100%;
max-width: 100%;
}
}
</style>
<body>
<h1>Responsive Image Grid Example</h1>
<div class="outer-grid">
<div class="inner-grid">
<img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
<img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
<img src="https://images.pexels.com/photos/1083822/pexels-photo-1083822.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<div class="inner-grid">
<img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
<img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
<img src="https://images.pexels.com/photos/3805102/pexels-photo-3805102.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<div class="inner-grid">
<img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
<img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
<img src="https://images.pexels.com/photos/3863778/pexels-photo-3863778.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
</div>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP