How can I centre multiple images that are floated across more than one line?

75 views Asked by At

I am using bootstrap and have a div that is "col-md-8 col-md-offset-2" which is in the centre of the page. Using php I am loading images (film posters) from a database in a while loop until all images are loaded. I have floated them and given them all margins to space them out a little, and they load on multiple lines. Above them is a centred h2 (the genre). How do I horizontally centre the images for each line? At the moment they align to the left of the div. I have tried a combination of things to centre them but none will have any affect.

Here is the code.

<div class="col-xs-8 col-xs-offset-2" id="genrecontent">
    <?php
        //get the genre name
        $genres = $db->query('SELECT name FROM genre WHERE id = '.($_GET['id']));
        $genre = $genres->fetch_object('genre');
    ?>
    <h2><?=$genre->name?></h2>
    <br/>
    <?php
        // get the films from the genre we are dealing with
        // ensuring we escape the GET string
        $films = $db->query('SELECT * FROM film WHERE genre_id = '.$db->real_escape_string($_GET['id']));
        while($film = $films->fetch_object('film')):
    ?>
    <a href="films.php?id=<?=$film->id?>">
        <img src="http://comp2203.ecs.soton.ac.uk/coursework/1415/assets/posters/<?=$film->id?>_medium.jpg" alt="film poster"/>
    </a>
    <?php
        endwhile;
    ?>
</div>

and here is the CSS

#genrecontent h2{
    text-align: center;
}

#genrecontent a{
    float: left;
}

#genrecontent img{
    width: 200px;
    height: 300px;
    margin: 15px;
}

I realise that usually I could set the width of the div and the widths of the images and their margins to make a perfect spacing out but the div changes size responsively corresponding to the browser size and so I need to work out a way to float and centre them.

1

There are 1 answers

0
Leo Bauza On

I misunderstood your question the first time around. To align multiple images on a line you want to set the display of the images to inline-block and then set the parent to text-align: center.

I made a fiddle that should help but your css would look like this:

img {
    width: 100px;
}
li {
    display: inline-block;
}
ul {
    list-style: none;
    text-align: center;
}

https://jsfiddle.net/bxurz66w/