Home  >  Article  >  Web Front-end  >  How to Center Two Images Horizontally with CSS?

How to Center Two Images Horizontally with CSS?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 10:52:02425browse

How to Center Two Images Horizontally with CSS?

Centering Two Images Horizontally with CSS

When attempting to align two images side by side, it's common to encounter instances where they stack vertically instead. To resolve this issue, we can modify the CSS code.

In the provided HTML code, two images are placed within anchor tags. The CSS code aims to center these images, but it unintentionally stacks them vertically. Let's adjust the CSS to achieve proper horizontal alignment.

The first modification is to change the display property of the images from "block" to "inline-block." Inline-block allows an element to be treated as a block (width and height can be set) while still behaving as an inline element.

<code class="css">#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}</code>

becomes:

<code class="css">.fblogo {
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}</code>

To further center the images correctly, we introduce a new CSS rule.

#images{
    text-align:center;
}

This rule aligns the content of the "images" div element, which contains the two image links, to the center.

Lastly, we need to update the HTML code to give both images a common class name, "fblogo," which is referenced in the modified CSS code. The modified HTML:

<code class="html"><div id="images">
    <a href="mailto:[email&#160;protected]">
    <img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
    </a>
    <a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
    <img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
    </a>
</div>​</code>

With these modifications, the two images will now be centered and displayed side by side.

The above is the detailed content of How to Center Two Images Horizontally with CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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