简体   繁体   中英

How to make a centered gallery layout with CSS and Javascript?

I am attempting to create an attractive layout for a series of equally-sized boxes. The number of boxes will vary. The idea is to flow the boxes into rows and columns to fill up a container; container size varies with the size of the web browser's window. Normally, you can do this easily with a float: left; for each of the boxes. Here is the wrinkle: I would like to have the last row, if it is uneven, be centered.

Example: Thirteen boxes. Three rows of four boxes, with the thirteenth box centered within the fourth row.

I'm almost positive this has leaped far out of the realm of CSS, even CSS3, but I was wondering if there were Javascript libraries or at least well-known algorithms for handling this kind of thing. I have some very brute force ideas about it but my guess is that someone else has already done this in a more elegant fashion.

Even something like being able to pick out a given box's row and column would be a great start.

Assuming that your <img /> is right inside the .row , it seems pretty easy to do something like:

.row:last-child {
  text-align: center;
}

If not, you can still use :last-child , only like:

.row:last-child .box {
  display:block;
  margin: 0 auto;
}

About actually generating HTML code itself, you didn't provide enough information to adress that matter, but hovewer you do it, either by generating only <img /> and wrapping every n-th of them in .row or by generating them inside .box , those styles are going to work.

You can use CSS flexbox like so:

 .flex-container { display: flex; flex-wrap: wrap; background-color: DodgerBlue; justify-content: center; } .flex-container > div { background-color: #f1f1f1; width: calc(25% - 20px); margin: 10px; text-align: center; line-height: 75px; font-size: 30px; } 
 <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM