Search code examples
htmlcssalignment

align images horizontally


How can I align images contained in a div horizontally? That is with a fixed width.

Example code:

HTML

<div id="random">
<a href=""><img src=".jpg" /><span></span></a>
<a href=".html"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p>
</div>

CSS

#random{ 
max-width: 650px
}

Solution

  • Usually floats can do the trick to align elements horizontally quite nicely. Use that inconjunction with clearfix class on the containing (parent) element so the floats don't break your other page layout.

    HTML

    <div class="horiz clearfix">
        <div><a href="www.google.com"><img src="https://www.pathe.nl/themes/main_theme/gfx/icons/placeholder-large.png"/>
            </a></div>
        <div><a href="www.stackoverflow.com"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p></div>
    </div>
    <div class="horiz clearfix">
        <div><a href="www.google.com"><img src="https://www.pathe.nl/themes/main_theme/gfx/icons/placeholder-large.png"/>
            </a></div>
        <div><a href="www.stackoverflow.com"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p></div>
    </div>​
    

    CSS

    /*
     * Clearfix: contain floats
     *
     * For modern browsers
     * 1. The space content is one way to avoid an Opera bug when the
     *    `contenteditable` attribute is included anywhere else in the document.
     *    Otherwise it causes space to appear at the top and bottom of elements
     *    that receive the `clearfix` class.
     * 2. The use of `table` rather than `block` is only necessary if using
     *    `:before` to contain the top-margins of child elements.
     */
    
    .clearfix:before,
    .clearfix:after {
        content: " "; /* 1 */
        display: table; /* 2 */
    }
    
    .clearfix:after {
        clear: both;
    }
    
    /*
     * For IE 6/7 only
     * Include this rule to trigger hasLayout and contain floats.
     */
    
    .clearfix {
        *zoom: 1;
    }
    
    .horiz > * {
      float: left;
      margin-right: 5px;
    }​