0

0

构建响应式图文布局:CSS Grid实践指南

碧海醫心

碧海醫心

发布时间:2025-11-27 13:00:11

|

703人浏览过

|

来源于php中文网

原创

构建响应式图文布局:CSS Grid实践指南

本教程将指导您如何利用css grid高效创建灵活且响应式的网页布局,特别是实现文本、图片和按钮的并排显示。我们将通过优化html结构、应用css grid属性,并结合响应式设计最佳实践,解决前端开发中常见的布局与适配问题,最终构建出在不同屏幕尺寸下均能良好呈现的专业级页面。

在现代网页设计中,创建既美观又能在各种设备上良好运行的响应式布局是一项核心技能。对于初学者而言,实现复杂的图文并排布局并确保其在不同屏幕尺寸下自适应,常常会遇到挑战。传统的浮动(float)或定位(position)方法虽然可以实现部分效果,但在维护性和灵活性方面往往不如现代CSS布局模块。CSS Grid(网格布局)提供了一种强大且直观的二维布局解决方案,能够轻松应对这类需求。

理解CSS Grid布局基础

CSS Grid是一种用于网页布局的强大工具,它允许开发者将页面内容划分为行和列,形成一个网格,然后将元素放置到这些网格单元中。其核心概念包括:

  • 网格容器(Grid Container):应用display: grid的父元素。
  • 网格项(Grid Items):网格容器的直接子元素。
  • 网格线(Grid Lines):构成网格的水平和垂直线。
  • 网格轨道(Grid Tracks):网格线之间的空间,可以是行或列。

通过定义网格容器的属性,我们可以精确控制网格项的排列和尺寸,从而实现复杂的响应式布局。

优化HTML结构以适应Grid布局

在应用CSS Grid之前,首先需要对HTML结构进行适当的调整,以更好地配合网格布局的需求。对于需要将文本、图片和按钮并排显示的情况,一个常见的做法是将相关联的元素进行分组。

立即学习前端免费学习笔记(深入)”;

考虑以下原始HTML结构:

<body>
    <div class="header">
        <h1>We found trip that suits you</h1>
        <h1>Kieve Summer Camp</h1>
        <h1>Nobleboro, USA</h1>    
    </div> 
    <div class="content">
       <p>
        Located on the shores of Lake Damariscotta in Maine, Kieve has been building boys' character and teaching them wilderness skills since 1926. With a heavy focus on excursions—only half the campers are usually on-site, with the other half exploring during the regular camping trips and half-day adventures—activities also include an extensive ropes course, lacrosse, baseball, woodworking, riflery, fishing, swimming, paddle boarding, windsurfing, sailing, tennis, soccer, and photography. A more traditional camp where each boy has a duty, plus takes part in daily activities such as a flag raising and evening prayer, campers are encouraged to try new activities and widen their comfort zones. A sister camp around the lake—Wavus Camp for Girls—operates under a similar philosophy, teaching bravery, resilience, and a reverence for nature.
        </p>  
        @@##@@  
    </div>
    <button class="button">Save</button>
    <button class="button">Randomize again</button>
</body>

为了实现文本在左侧,图片和按钮在右侧的布局,我们需要将图片和两个按钮封装在一个新的容器中。同时,为了更好地控制页面的整体宽度和居中,建议在body内部添加一个全局的wrapper容器。

优化后的HTML结构示例:

<body>
    <div class="wrapper">
        <div class="header">
            <h1>We found trip that suits you</h1>
            <h1>Kieve Summer Camp</h1>
            <h1>Nobleboro, USA</h1>    
        </div> 
        <div class="content">
           <p>
            Located on the shores of Lake Damariscotta in Maine, Kieve has been building boys' character and teaching them wilderness skills since 1926. With a heavy focus on excursions—only half the campers are usually on-site, with the other half exploring during the regular camping trips and half-day adventures—activities also include an extensive ropes course, lacrosse, baseball, woodworking, riflery, fishing, swimming, paddle boarding, windsurfing, sailing, tennis, soccer, and photography. A more traditional camp where each boy has a duty, plus takes part in daily activities such as a flag raising and evening prayer, campers are encouraged to try new activities and widen their comfort zones. A sister camp around the lake—Wavus Camp for Girls—operates under a similar philosophy, teaching bravery, resilience, and a reverence for nature.
            </p>  
            <div class="right-col">
                @@##@@  
                <div class="buttons-group">
                    <button class="button">Save</button>
                    <button class="button">Randomize again</button>
                </div>
            </div>
        </div>
    </div>
</body>

这里我们将图片和按钮进一步嵌套在right-col中,并为按钮创建了一个buttons-group容器,这为后续的布局和样式控制提供了更大的灵活性。

一帧秒创
一帧秒创

基于秒创AIGC引擎的AI内容生成平台,图文转视频,无需剪辑,一键成片,零门槛创作视频。

下载

应用CSS Grid实现布局

现在,我们可以利用CSS Grid来定义.content区域的布局。

CSS样式示例:

body {
    margin: 0;
    background-color: #353535;
    font-family: 'Inter', serif; /* 统一字体 */
    color: white; /* 统一文本颜色 */
}

.wrapper {
    max-width: 1200px; /* 限制页面最大宽度 */
    margin: 0 auto; /* 页面居中 */
    padding: 20px; /* 内边距 */
}

.header {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    width: 100%; /* 在wrapper内占满宽度 */
    height: 150px;
    background-color: #3C6E71;
    border-radius: 25px;
    display: flex; /* 使用Flexbox居中h1 */
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px; /* 与下方内容保持距离 */
}

.header h1 {
    margin: 3px 0; /* 调整h1的上下边距 */
}

.content {
    display: grid; /* 启用CSS Grid布局 */
    grid-template-columns: repeat(2, 1fr); /* 定义两列,每列占据可用空间的1份 */
    gap: 2em; /* 列间距 */
    padding: 10px;
    background-color: #353535; /* 保持背景色一致 */
    align-items: start; /* 网格项顶部对齐 */
}

.content p {
    margin: 0; /* 移除默认边距 */
    line-height: 1.6; /* 增加行高提高可读性 */
}

.right-col {
    display: flex; /* 使用Flexbox布局图片和按钮组 */
    flex-direction: column; /* 垂直堆叠 */
    gap: 1em; /* 元素间距 */
    align-items: center; /* 水平居中 */
}

.content img {
    max-width: 100%; /* 图片最大宽度为其父容器的100% */
    height: auto; /* 高度自动调整以保持图片比例 */
    object-fit: cover;
    border: 3px solid white;
    border-radius: 8px; /* 添加圆角 */
}

.buttons-group {
    display: flex; /* 按钮组内部使用Flexbox */
    gap: 10px; /* 按钮间距 */
    margin-top: 10px; /* 与图片保持距离 */
}

.button {
    background-color: #D9D9D9; 
    border: none;
    color: #D00000;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 13px;
    cursor: pointer;
    font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    border-radius: 5px; /* 添加圆角 */
    transition: background-color 0.3s ease; /* 添加过渡效果 */
}

.button:hover {
    background-color: #c0c0c0; /* 悬停效果 */
}

关键CSS Grid属性解释:

  • display: grid;:将.content元素转换为一个网格容器。
  • grid-template-columns: repeat(2, 1fr);:定义了两列。repeat(2, ...)表示重复两次,1fr表示“一份可用空间”。这意味着两列将平分.content容器的宽度。使用1fr比固定的50%在处理gap时更灵活。
  • gap: 2em;:设置网格行和列之间的间距。
  • align-items: start;:将网格项在其网格区域内沿垂直方向的起始位置对齐。

增强整体响应性

为了确保页面在小屏幕设备上也能有良好的用户体验,我们需要引入媒体查询(Media Queries)来调整布局。

添加媒体查询:

/* 针对小屏幕设备(例如,宽度小于768px) */
@media (max-width: 768px) {
    .content {
        grid-template-columns: 1fr; /* 在小屏幕上变为单列布局 */
        gap: 1em; /* 调整间距 */
    }

    .right-col {
        align-items: stretch; /* 填充可用宽度 */
    }

    .buttons-group {
        flex-direction: column; /* 按钮垂直堆叠 */
        width: 100%; /* 按钮组宽度占满 */
    }

    .button {
        width: 100%; /* 按钮宽度占满 */
        box-sizing: border-box; /* 包含padding和border在宽度内 */
    }

    .header {
        height: auto; /* 头部高度自适应 */
        padding: 15px;
    }
}

在上述媒体查询中:

  • 当屏幕宽度小于或等于768px时,.content的布局会从两列变为单列(grid-template-columns: 1fr;),使内容垂直堆叠,更适合移动设备阅读。
  • right-col和buttons-group的Flexbox布局也进行了调整,以确保图片和按钮能够更好地适应单列布局。

完整代码示例

将以上HTML和CSS代码整合,即可得到一个功能完善的响应式图文布局页面。

HTML (index.html):

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应式图文布局教程</title>
    <link rel="stylesheet" href="index.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
    <div class="wrapper">
        <div class="header">
            <h1>We found trip that suits you</h1>
            <h1>Kieve Summer Camp</h1>
            <h1>Nobleboro, USA</h1>    
        </div> 
        <div class="content">
           <p>
            Located on the shores of Lake Damariscotta in Maine, Kieve has been building boys' character and teaching them wilderness skills since 1926. With a heavy focus on excursions—only half the campers are usually on-site, with the other half exploring during the regular camping trips and half-day adventures—activities also include an extensive ropes course, lacrosse, baseball, woodworking, riflery, fishing, swimming, paddle boarding, windsurfing, sailing, tennis, soccer, and photography. A more traditional camp where each boy has a duty, plus takes part in daily activities such as a flag raising and evening prayer, campers are encouraged to try new activities and widen their comfort zones. A sister camp around the lake—Wavus Camp for Girls—operates under a similar philosophy, teaching bravery, resilience, and a reverence for nature.
            </p>  
            <div class="right-col">
                @@##@@  
                <div class="buttons-group">
                    <button class="button">Save</button>
                    <button class="button">Randomize again</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

CSS (index.css):

body {
    margin: 0;
    background-color: #353535;
    font-family: 'Inter', serif;
    color: white;
}

.wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.header {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
    width: 100%;
    height: 150px;
    background-color: #3C6E71;
    border-radius: 25px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
}

.header h1 {
    margin: 3px 0;
}

.content {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 2em;
    padding: 10px;
    background-color: #353535;
    align-items: start;
}

.content p {
    margin: 0;
    line-height: 1.6;
}

.right-col {
    display: flex;
    flex-direction: column;
    gap: 1em;
    align-items: center;
}

.content img {
    max-width: 100%;
    height: auto;
    object-fit: cover;
    border: 3px solid white;
    border-radius: 8px;
}

.buttons-group {
    display: flex;
    gap: 10px;
    margin-top: 10px;
}

.button {
    background-color: #D9D9D9; 
    border: none;
    color: #D00000;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 13px;
    cursor: pointer;
    font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
    border-radius: 5px;
    transition: background-color 0.3s ease;
}

.button:hover {
    background-color: #c0c0c0;
}

/* 媒体查询 */
@media (max-width: 768px) {
    .content {
        grid-template-columns:
Italian TrulliCamp ImageCamp Image

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
css中float用法
css中float用法

css中float属性允许元素脱离文档流并沿其父元素边缘排列,用于创建并排列、对齐文本图像、浮动菜单边栏和重叠元素。想了解更多float的相关内容,可以阅读本专题下面的文章。

595

2024.04.28

C++中int、float和double的区别
C++中int、float和double的区别

本专题整合了c++中int和double的区别,阅读专题下面的文章了解更多详细内容。

106

2025.10.23

堆和栈的区别
堆和栈的区别

堆和栈的区别:1、内存分配方式不同;2、大小不同;3、数据访问方式不同;4、数据的生命周期。本专题为大家提供堆和栈的区别的相关的文章、下载、课程内容,供大家免费下载体验。

443

2023.07.18

堆和栈区别
堆和栈区别

堆(Heap)和栈(Stack)是计算机中两种常见的内存分配机制。它们在内存管理的方式、分配方式以及使用场景上有很大的区别。本文将详细介绍堆和栈的特点、区别以及各自的使用场景。php中文网给大家带来了相关的教程以及文章欢迎大家前来学习阅读。

605

2023.08.10

CSS position定位有几种方式
CSS position定位有几种方式

有4种,分别是静态定位、相对定位、绝对定位和固定定位。更多关于CSS position定位有几种方式的内容,可以访问下面的文章。

83

2023.11.23

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

22

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

48

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

93

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

216

2026.03.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.9万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

CSS教程
CSS教程

共754课时 | 42.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号