TechTorch

Location:HOME > Technology > content

Technology

Aligning Text Below an Image in HTML and CSS: A Comprehensive Guide

May 27, 2025Technology4577
Aligning Text Below an Image in HTML and CSS: A Comprehensive Guide Ma

Aligning Text Below an Image in HTML and CSS: A Comprehensive Guide

Mastering the art of aligning text below an image in HTML and CSS is essential for creating visually appealing web designs. This guide will provide you with step-by-step instructions and examples using both div and figure elements. Let's dive into these methods and see which one suits your needs best.

Method 1: Using div

!DOCTYPE html
html langen
head
    meta charsetUTF-8
    meta nameviewport contentwidthdevice-width, initial-scale1.0
    meta http-equivX-UA-Compatible contentieedge
    titleText Below Image/title
    style
        .container {
            text-align: center;
            margin: 20px;
        }
        img {
            max-width: 100%;
            height: auto;
        }
    /style
/head
body
    div classcontainer
        img src altSample Image
        pYour text goes here./p
    /div
/body
/html

In this method, we use a container div to hold the image and the text. The .container class centers the text and adds some margin for better visual separation.

Method 2: Using figure

!DOCTYPE html
html langen
head
    meta charsetUTF-8
    meta nameviewport contentwidthdevice-width, initial-scale1.0
    meta http-equivX-UA-Compatible contentieedge
    titleText Below Image/title
    style
        figure {
            text-align: center;
            margin: 20px;
        }
        img {
            max-width: 100%;
            height: auto;
        }
    /style
/head
body
    figure
        img src altSample Image
        figcaptionYour text goes here./figcaption
    /figure
/body
/html

This method uses a figure element to contain both the image and the text. The figure class centers the text and adds margin. The figcaption tag is used to wrap the text, making it semantically meaningful. This approach is particularly useful when the text is a caption describing the image.

Responsive Images

Both methods ensure that the images are responsive and scale properly on different screen sizes using the max-width: 100% and height: auto properties. These properties maintain the image's aspect ratio and ensure that it doesn’t stretch or distort.

Optional Customizations

If you want to ensure that the text is centered, you can customize the CSS as follows:

style
    .img-with-text { text-align: center }
/style

Adding this class to the div or figure will center the text, regardless of its width. Alternatively, if you want to float the div itself, you can do so by adding the following CSS:

style
    .img-with-text { 
        text-align: center;
        width: auto;
        float: left;
    }
/style

This technique allows the content to remain centered without specifying a width, which can be particularly useful for fluid layouts.