How to center the vertical position of an image with display:flex (memo)

PubDate:

/ ModDate:

WordPressのトラブル対処方法の画像

<Description based on the Act on Premiums and Representations> The content on this site may include product promotions.



This is a memo on what to do when the top and bottom margins of the image do not match even though the vertical position is centered with “display:flex” + “align-items:center;”

Please note that this is a complete style memo, so there may be errors depending on the case.

“display:flex;” is often used when you want to arrange elements horizontally in HTML like the one below.

<div class="pwcn-parent">
    <div class="child-a">
        <img src=""....>
    </div>
    <div class="child-b">
        <p>Text</p>
    </div>
</div>

If you want to align the vertical position to the center, specifically write it like this.

.pwcn-parent {
    /* display: flex; */
    display: flex;
    align-items: center;
    justify-content: left;
    border: 1px solid #000;
    padding: 8px;
    background:#000;
    color:#fff;
}

Below is a display sample with the above HTML and style code added.

Display sample where the top and bottom margins of the image are slightly different

abcdefg

….I intentionally made the background black, but do you notice that there is a slight difference between the black parts at the top and bottom of the image?

Well, about this. .. That’s what I want to say, but if you want to fix it anyway, if you have the above structure, you can solve it by adding the following style code.

.child-a img {
    display: block;
    margin: auto 0;/* This may not be necessary */
}

By the way, the following is what I added (class names have been changed so you can see the difference).

Display sample with the top and bottom margins of images aligned

abcdefg

Hmm, that feels good.

The above is an example of what to do when the gap between the top and bottom of the image is not centered when using display:flex;.


This page is an English translation of the Japanese page. The information on the Japanese page may be more accurate because we maintain the Japanese page as the basis and not all content matches.
You can view the Japanese page by clicking the “View Japanese Page” button on the top right of the page, so please take a look.

If you found the content posted on this page or the reference code introduced helpful, please leave a comment in the comment section at the end of the page, or spread the word on SNS etc.

The methods and codes posted on this page have been confirmed to work in my environment as of the last update date. Please note that in principle, we will not respond even if we receive information about malfunctions or detailed customization methods in the comments section.

Until the end Thank you for reading.

The copyright and ownership of all content published on this page, including texts, images, and codes, belongs to this site, and reproduction is strictly prohibited.