简体   繁体   中英

Fluid grid with aligned columns (HTML, CSS)

I'm trying to create a grid of equally sized boxes that always take up the full width of the container while staying vertically aligned. One way to do it is to calculate width and margins based on the container width, but in a way it feels clumsy to do it like that. It turned out to be hard with a flexbox solution as well to both expand the boxes to take up the full width and keeping the last row aligned with the others even if it has less elements in it.

I also made a small JSFiddle to start from if anyone feels like playing around. Fiddle 网格示例

'

I'd try something with columns instead of flexbox...

 .container { width:100%; column-count:999; column-width:7em; column-gap: 0.1em; } .box { -webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */ page-break-inside: avoid; /* Firefox */ break-inside: avoid; /* IE 10+ */ height: 3em; width: 100%; margin-bottom: 0.1em; background-color: lightgray; } 
 <div id="containerId" class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> 

What's about this solution ?

 .container { display: flex; flex-wrap: wrap; } .box { height: 3em; width: 7em; margin: 0.1em; background-color: lightgray; flex: 0 0 auto; } 
 <div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></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