简体   繁体   中英

Align all items horizontally to the left with CSS grid

  1. I have an unknown number of items and I want them stacked horizontally to the left

  2. I want a fixed gap between the items

  3. The width of the items is unknown, and could have variations

I know I could use flex like below, but I'd like to know if this accomplishable with grid .

 #box { display: flex; width: 300px; outline: 1px solid blue; }.item { background: gray; width: 50px; height: 100px; } #box > * + * { margin-left: 10px; }
 <div id='box'> <div class='item'></div> <div class='item'></div> <div class='item'></div> <div class='item'></div> </div>

Update

Increased the width value for the parent, to display clearer what I'm going after - the children should not take up the full parent width (unless there are many children of course).

Here. I used the same measures and sizes from your example.

Depends on children width

 #box { display: inline-grid; grid-auto-flow: column; grid-template-columns: auto; grid-auto-rows: 100px; column-gap: 10px; outline: 1px solid blue; }.item { background: gray; width: 50px; }
 <div id='box'> <div class='item'></div> <div class='item'></div> <div class='item'></div> <div class='item'></div> </div>

Depends on parent width

 #box { display: grid; grid-auto-flow: column; grid-template-columns: auto; grid-auto-rows: 100px; column-gap: 10px; outline: 1px solid blue; width: 230px; }.item { background: gray; }
 <div id='box'> <div class='item'></div> <div class='item'></div> <div class='item'></div> <div class='item'></div> </div>

UPDATED

Wen the size of parent is 100% width and number of children is indefinite.

 #box { width: 100%; display: grid; grid-template-columns: repeat(auto-fill, 50px); grid-auto-rows: 100px; column-gap: 10px; outline: 1px solid blue; }.item { background: gray; }
 <div id='box'> <div class='item'></div> <div class='item'></div> <div class='item'></div> <div class='item'></div> </div>

Now we know, your case can be solved with grid , but I suggest you to use flex . Using grid for this task is like hitting a screw with a hammer - we can reach a goal, but using wrong tool. Grid is more useful for tables with unusual pattern of sells, better if we know the number of columns. And Flex more useful for lists of elements, like in your case. Although Flex is older and more native then Grid , works a lot more stable in all modern browsers.

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