Ankit
Ankit

Reputation: 6980

How to arrange images as a grid with variable number of columns?

I currently have an HTML page that contains images and some text in a vertical sequential order.

<div>
 <img src="img/img1.jpg"/>
 Dr. XYZ
</div>

<div>
 <img src="img/img1.jpg"/>
 Dr. XYZ
</div>

<div>
 <img src="img/img1.jpg"/>
 Dr. XYZ
</div>

What I am trying to do is to arrange the images into grids. I know I can use tables with two columns if I want to create the grid with two columns.

However, I do not want to hard-code this? Is there an alternate way using Javascript/CSS only to have a bunch of divs and then arrange them as a grid with arbitrary number of columns so that I don't have to restructure the whole page every time I want to change the number of grids.

Upvotes: 0

Views: 789

Answers (2)

Stanko
Stanko

Reputation: 520

You could change the following to display them in a grid-like pattern

<div style"display:inline-block; float:left">
    <img src="img/img1.jpg"/>
    Dr. XYZ
</div>

You can then control the number of rows by changing the width of the DIV that contains the DIVs with images.

<div id="container" style="width:500px">
    <div style"display:inline-block; float:left">
        <img src="img/img1.jpg"/>
        Some text 1
    </div>
    <div style"display:inline-block; float:left">
        <img src="img/img2.jpg"/>
        Some text 2
    </div>
</div>

Upvotes: 1

Ibu
Ibu

Reputation: 43810

Yes you can; here is an example:

<div class="parent">
   <div class="item">
     <img src="img/img1.jpg"/>
     Dr. XYZ
   </div>
   <div class="item">
     <img src="img/img1.jpg"/>
     Dr. XYZ
   </div>
   <div class="item">
     <img src="img/img1.jpg"/>
     Dr. XYZ
   </div>
   ....
   <div class="clear"></div>
</div>

Your css:

.parent {
   width:900px; /** Just an example **/
}
.clear {
   clear:both;
}

.item {
    float:left;
    width:150px; /** Just an example **/
    margin:3px;
}

Now your divs with images will all be in a column 150px wide

Upvotes: 0

Related Questions