Table of Contents
Understanding the problem: the default behavior of figcaption
Solution: inline-block container
HTML structure
CSS Style
Complete sample code
Further optimization and precautions
Home Web Front-end HTML Tutorial HTML/CSS realizes multi-graph grid layout and title alignment

HTML/CSS realizes multi-graph grid layout and title alignment

Aug 13, 2025 pm 06:57 PM

HTML/CSS realizes multi-graph grid layout and title alignment

This tutorial aims to solve the problem of implementing multiple images in HTML in a grid and displaying the corresponding text below each image. We will explore the reasons why figcaption is a block-level element that causes layout misalignment, and provide a solution based on the display: inline-block attribute, which can achieve flexible and responsive side-by-side display of graphics and text by creating a unified packaging container for images and titles.

Understanding the problem: the default behavior of figcaption

In web design, we often need to display image galleries or product lists, with short descriptive text below each image. Beginners may try to place HTML/CSS realizes multi-graph grid layout and title alignment tags and

tags directly side by side, expecting that they can be arranged in multiple columns automatically. For example:

 <img  src="/static/imghw/default1.png" data-src="img1.png" class="lazy" alt="HTML/CSS realizes multi-graph grid layout and title alignment" > <figcaption> "Image 1 Title" </figcaption>
<img  src="/static/imghw/default1.png" data-src="img2.png" class="lazy" alt="HTML/CSS realizes multi-graph grid layout and title alignment" > <figcaption> "Image 2 Title" </figcaption>

However, this practice often results in each image and its title being exclusive to one line rather than being displayed side by side. This is because the

element is a block-level element in HTML by default. Block-level elements occupy the entire width of their parent container and force the subsequent content to be displayed on a new line. Therefore, even if the picture itself is an in-line replacement element, the block-level nature of figcaption destroys the expected multi-column layout.

Solution: inline-block container

To solve this problem, we need to treat each image and its corresponding title as an independent "unit" that can be arranged side by side. The most effective way is to create a common wrapper container for each group of images and titles, and use the display: inline-block property of CSS to control the layout of these containers.

display: inline-block is a very powerful CSS attribute that combines the characteristics of in-line elements and block-level elements:

  • In-line characteristics: Elements can be displayed side by side in the same line like text, and will automatically wrap when there is insufficient space.
  • Block-level properties: Elements can set block-level properties such as width (width), height (height), inner and outer margin (margin, padding), and the contents inside can be laid out according to the rules of block-level elements.

By wrapping the image and title in a div (or a more semantic

element) and applying display: inline-block to this wrapper container, we can achieve the desired grid layout.

HTML structure

We wrap each image and its title in a div and add a class name to it, such as image-wrapper:

 <div class="gallery-container">
    <div class="image-wrapper">
        <img src="/static/imghw/default1.png" data-src="img1.png" class="lazy" alt="picture 1">
        <figcaption>Image 1 Title</figcaption>
    </div>
    <div class="image-wrapper">
        <img src="/static/imghw/default1.png" data-src="img2.png" class="lazy" alt="picture 2">
        <figcaption>Image 2 Title</figcaption>
    </div>
    <div class="image-wrapper">
        <img src="/static/imghw/default1.png" data-src="img3.png" class="lazy" alt="picture 3">
        <figcaption>Picture 3 title</figcaption>
    </div>
    <!-- More pictures and titles-->
</div>

Note: For better semanticization, it is recommended to use the

element as a wrapper for pictures and titles, and
is a child element of
. The above example of div is to directly correspond to the original question and answer solution, but in actual development,
is the better choice.

CSS Style

Next, we add CSS style to the .image-wrapper class:

 <style>
    .gallery-container {
        text-align: center; /* Optional: center all image groups in the parent container*/
    }

    .image-wrapper {
        display: inline-block; /* Key: Make the picture group display side by side*/
        text-align: center; /* center the image and title inside its container*/
        margin: 10px; /* Optional: Set the spacing between picture groups*/
        vertical-align: top; /* Optional: Align the top to avoid misalignment due to different content height*/
        width: calc(33.33% - 20px); /* Example: Three column layout, minus left and right margin */
        max-width: 250px; /* limit the maximum width of each picture*/
    }

    .image-wrapper img {
        max-width: 100%; /* Make sure the image is scaled responsively within its container*/
        height: auto; /* Keep picture aspect ratio*/
        display: block; /* Ensure that the picture is independent and avoid bottom gaps*/
        margin: 0 auto 5px; /* The picture is centered and spaced from the title*/
    }

    .image-wrapper figcaption {
        font-size: 0.9em;
        color: #555;
        padding: 5px;
    }

    /* Responsive adjustment (optional) */
    @media (max-width: 768px) {
        .image-wrapper {
            width: calc(50% - 20px); /* Medium screen displays two columns*/
        }
    }

    @media (max-width: 480px) {
        .image-wrapper {
            width: calc(100% - 20px); /* Small screen displays a column*/
        }
    }
</style>

Key CSS attribute explanation:

  • display: inline-block;: This is the core of implementing side-by-side layout.
  • text-align: center;: Applied inside .image-wrapper so that the image and title are centered horizontally within their respective containers.
  • margin: 10px;: Add external spacing to each image group so that it does not fit tightly.
  • vertical-align: top;: When the contents of the inline-block elements are different in height, this property ensures that they are aligned at the top and avoids uneven bottoms.
  • width: calc(33.33% - 20px);: This is an example to implement a three-column layout. The calc() function allows mathematical calculations in CSS, where the width of each column is calculated and the left and right margins are subtracted.
  • max-width: 100%; and height: auto;: Applied to img tags, ensuring that the image can be automatically adjusted according to the size of its parent container in a responsive layout and maintains its original aspect ratio.
  • display: block; (for img): Although img is an inline replacement element, setting it to display: block eliminates extra blanks that may appear under the image (usually caused by baseline alignment) and makes it easier to center through margin: 0 auto.

Complete sample code

Combine HTML structure and CSS styles and you will get a functionally complete picture grid layout:

 


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Picture and Title Grid Layout</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }

        .gallery-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 10px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center; /* center all image groups in the parent container*/
        }

        .image-wrapper {
            display: inline-block; /* Key: Make the picture group display side by side*/
            text-align: center; /* center the image and title inside its container*/
            margin: 10px; /* Set the spacing between picture groups*/
            vertical-align: top; /* Align top*/
            width: calc(33.33% - 20px); /* Example: Three column layout, minus left and right margin */
            min-width: 150px; /* Minimum width to prevent too small*/
            box-sizing: border-box; /* Make sure padding and border are included in the width*/
        }

        .image-wrapper img {
            max-width: 100%; /* Make sure the image is scaled responsively within its container*/
            height: auto; /* Keep picture aspect ratio*/
            display: block; /* Ensure that the picture is independent of the placeholder*/
            margin: 0 auto 8px; /* The picture is centered and spaced from the title*/
            border-radius: 4px;
        }

        .image-wrapper figcaption {
            font-size: 0.9em;
            color: #333;
            padding: 0 5px;
            line-height: 1.4;
        }

        /* Responsive adjustment*/
        @media (max-width: 768px) {
            .image-wrapper {
                width: calc(50% - 20px); /* Medium screen displays two columns*/
            }
        }

        @media (max-width: 480px) {
            .image-wrapper {
                width: calc(100% - 20px); /* Small screen displays a column*/
            }
        }
    </style>



    <div class="gallery-container">
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x180/FF5733/FFFFF?text=Image%201" alt="Beautiful Landscape 1">
            <figcaption>This is a beautiful landscape that shows the charm of nature. </figcaption>
        </div>
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x200/33FF57/FFFFF?text=Image%202" alt="City Night View 2">
            <figcaption>The city under the night sky is brightly lit and full of light. </figcaption>
        </div>
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x160/3357FF/FFFFF?text=Image%203" alt="Abstract Art Works 3">
            <figcaption> An abstract art work full of imagination, which is thought-provoking. </figcaption>
        </div>
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x190/FF33A1/FFFFF?text=Image%204" alt="Cute Little Animal 4">
            <figcaption> A furry kitten is exploring the world curiously. </figcaption>
        </div>
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x170/A133FF/FFFFFF?text=Image%205" alt="Food Close-up 5">
            <figcaption>The seductive close-up of the food makes people salivate. </figcaption>
        </div>
        <div class="image-wrapper">
            <img src="https://via.placeholder.com/250x210/33FFF3/FFFFF?text=Image%206" alt="Technology Product Display 6">
            <figcaption>The latest smartphone, with exquisite design and powerful functions. </figcaption>
        </div>
    </div>


Further optimization and precautions

  1. Semantic HTML: As mentioned earlier, it is more recommended to use a combination of

    and
    because they are designed specifically for independent content blocks such as pictures, charts, codes, and their titles. Replace div.image-wrapper with figure and make sure figcaption is a direct child of figure.

     <figure class="image-wrapper">
        <img src="/static/imghw/default1.png" data-src="img1.png" class="lazy" alt="picture 1">
        <figcaption>Image 1 Title</figcaption>
    </figure>

    The CSS style remains unchanged because the figure is also a block-level element by default, and display: inline-block is also required.

  2. Responsive layout: inline-block itself has certain responsiveness. When the browser window width is insufficient, the element will automatically wrap. Combining width: calc() and media query (@media) allows for finer responsive control, such as displaying different numbers of columns under different screen sizes.

  3. Spacing control: Use margin attribute to control horizontal and vertical spacing between picture groups. To avoid extra spacing on the right side of the last column or extra spacing on the left side of the first column, consider using the padding and negative margin tricks of the parent container, or a more modern Flexbox/CSS Grid layout.

  4. Image size management: Be sure to set max-width: 100%; and height: auto; for img tags, which ensures that the image is scaled equally within its container and avoids overflow or deformation.

  5. Alternative layout solutions: Flexbox and CSS Grid: For more complex grid layout requirements, Flexbox and CSS Grid are more powerful and flexible tools.

    • Flexbox: Suitable for one-dimensional layouts (rows or columns), it allows easy control of the alignment, spacing and order of child elements.
    • CSS Grid: Applicable to two-dimensional layouts (rows and columns), you can directly define the rows and columns of the grid to achieve a more complex layout structure. When you need to have a more granular control over the number of columns, row heights, and cell spacing, you can consider learning and using these two modern layout techniques.
  6. Accessibility: Always provide meaningful alt attributes for HTML/CSS realizes multi-graph grid layout and title alignment tags. This is not only helpful for search engine optimization, but more importantly, it can provide visually impaired users with text descriptions of image content and improve the accessibility of the website.

With the above methods, you can efficiently achieve a beautiful and responsive picture grid layout in the webpage and clearly display its descriptive text under each image.

The above is the detailed content of HTML/CSS realizes multi-graph grid layout and title alignment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1509
276
The `` vs. `` in HTML The `` vs. `` in HTML Jul 19, 2025 am 12:41 AM

It is a block-level element, used to divide large block content areas; it is an inline element, suitable for wrapping small segments of text or content fragments. The specific differences are as follows: 1. Exclusively occupy a row, width and height, inner and outer margins can be set, which are often used in layout structures such as headers, sidebars, etc.; 2. Do not wrap lines, only occupy the content width, and are used for local style control such as discoloration, bolding, etc.; 3. In terms of usage scenarios, it is suitable for the layout and structure organization of the overall area, and is used for small-scale style adjustments that do not affect the overall layout; 4. When nesting, it can contain any elements, and block-level elements should not be nested inside.

How to add an image in HTML? How to add an image in HTML? Jul 15, 2025 am 03:03 AM

The key to adding images in HTML is to use the img tag and set the properties correctly. First, you must use the tag and set the src attribute to specify the image path. Secondly, it is recommended to add the alt attribute to provide alternative text; the path can be a relative path or an absolute path, and you need to pay attention to case, format support and server configuration; in addition, the picture style can be controlled through CSS to enhance responsiveness and aesthetics.

Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

Preloading Resources with HTML `link rel='preload'` Preloading Resources with HTML `link rel='preload'` Jul 19, 2025 am 12:54 AM

linkrel="preload" is a technology that optimizes page loading performance and is used to load critical resources in advance. Its core purpose is to prioritize loading of resources that are critical to home screen rendering, such as fonts, key CSS/JS and home screen images. Pay attention to when using: 1. Set the as attribute correctly to specify the resource type; 2. Avoid abuse and prevent excessive bandwidth usage; 3. Ensure that the resources will be actually used, otherwise it will cause waste of requests; 4. Add crossorigin attribute to cross-domain resources. Incorrect writing method such as the lack of the as attribute will cause the preload to be invalid. Rational use can improve page loading efficiency, otherwise it may be counterproductive.

What are the different types of lists available in html and their usage? What are the different types of lists available in html and their usage? Jul 15, 2025 am 02:59 AM

HTML provides three list types to structure content. 1. Unordered list () is used for entries that require no order, such as function list or ingredients; 2. Ordered list () is used for sequential content, such as step description, and supports multiple numbering formats; 3. Description list (,,) is used to pair terms and descriptions, such as dictionaries or product specifications; in addition, it also supports nested lists, which can add sublists under the main entry to organize complex information, thereby improving page readability and accessibility.

Shadow DOM Concepts and HTML Integration Shadow DOM Concepts and HTML Integration Jul 24, 2025 am 01:39 AM

ShadowDOM is a technology used in web component technology to create isolated DOM subtrees. 1. It allows the mount of an independent DOM structure on ordinary HTML elements, with its own styles and behaviors, and does not affect the main document; 2. Created through JavaScript, such as using the attachShadow method and setting the mode to open; 3. When used in combination with HTML, it has three major features: clear structure, style isolation and content projection (slot); 4. Notes include complex debugging, style scope control, performance overhead and framework compatibility issues. In short, ShadowDOM provides native encapsulation capabilities for building reusable and non-polluting UI components.

Can you put a  tag inside another  tag? Can you put a tag inside another tag? Jul 27, 2025 am 04:15 AM

❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

See all articles