简体   繁体   English

如何使用CSS和Javascript创建居中的画廊布局?

[英]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. 容器的大小随Web浏览器窗口的大小而变化。 Normally, you can do this easily with a float: left; 通常,您可以使用float: left;轻松完成此操作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. 我几乎肯定地说,这已经远远超出了CSS领域,甚至CSS3,但是我想知道是否存在Javascript库或至少知名的算法来处理这种事情。 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: 假设您的<img />就在.row内部, .row似乎很容易:

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

If not, you can still use :last-child , only like: 如果没有,您仍然可以使用:last-child ,仅类似于:

.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. 关于实际生成HTML代码本身,您没有提供足够的信息来解决这一问题,但您只能通过生成<img />并将它们的每n个包装在.row或通过在内部将它们生成而.row .box ,这些样式将起作用。

You can use CSS flexbox like so: 您可以像这样使用CSS flexbox

 .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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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