Home >Web Front-end >HTML Tutorial >How to create a responsive image grid layout using HTML and CSS
How to create a responsive image grid layout using HTML and CSS
In today’s Internet era, images occupy an important part of web content. In order to display various types of images, we need an effective and beautiful grid layout. In this article, we will learn how to create a responsive image grid layout using HTML and CSS.
First, we will create a basic structure using HTML. The following is the sample code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>响应式图片网格布局</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="grid-container"> <div class="grid-item"> <img src="image1.jpg" alt="图片1"> </div> <div class="grid-item"> <img src="image2.jpg" alt="图片2"> </div> <div class="grid-item"> <img src="image3.jpg" alt="图片3"> </div> <!-- ... --> </div> </body> </html>
In the above sample code, we create a <div> element with class <code>grid-container
, which contains Several child elements with class grid-item
, each child element contains a <img alt="How to create a responsive image grid layout using HTML and CSS" >## with
src and
alt attributes. #element.
Next, we need to use CSS to define and layout the grid. The following is the sample code:
.grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: 10px; } .grid-item { width: 100%; padding-top: 100%; position: relative; overflow: hidden; } .grid-item img { width: 100%; height: 100%; object-fit: cover; position: absolute; top: 0; left: 0; }In the above sample code, we first use
display: grid to convert the
grid-container element into a grid layout container. Then, we used
grid-template-columns to define the column layout of the grid, and achieved adaptive responsiveness through
repeat(auto-fit, minmax(200px, 1fr)) Layout, setting the minimum width of each column to 200 pixels and filling the available space as much as possible.
grid-gap to define the gap between grid items as 10 pixels.
.grid-item class, we use some styles to ensure that the grid items occupy equal space and to make the image adaptable. By setting
padding-top to a percentage value, we make the height of each grid item consistent with its width.
.grid-item img, including setting the width and height to 100%, using
object-fit: cover to make the image Fill the entire container as much as possible and position the image on the top and left of the container via
position: absolute.
The above is the detailed content of How to create a responsive image grid layout using HTML and CSS. For more information, please follow other related articles on the PHP Chinese website!