Multiple flexboxes with margin-right, except the l

2019-07-21 05:02发布

See the following image:

enter image description here

Current setup is at top-left. If I add more red boxes, they will wrap to the next line, leaving a 10px right margin of the last red box on the first line.

My question:

Is there any way to get the top-right example, as well as the nice-to-haves, with flex-boxes, but without resorting to JS, display:table, or negative margin shenanigans?

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-21 05:35

Yes, just use .red-box:not(:last-child) as your CSS selector, instead of .red-box only.

To make it work for multiple rows, all you have to do is wrap each row within a div. See this fiddle.

查看更多
乱世女痞
3楼-- · 2019-07-21 05:38

Since in the image you use width: 25%, I assume you want 4 element per line.

Therefore, you only need

.red-box {
    width: calc(25% - 30px/4);
    margin: 0 10px 10px 0;
}
.red-box:nth-child(4n) {
    margin-right: 0;
}

#wrapper {
    display: flex;
    flex-wrap: wrap;
    background: #01FF00;
}
.red-box {
    width: calc(25% - 30px/4);
    margin: 0 10px 10px 0;
    height: 100px;
    background: red;
}
.red-box:nth-child(4n) {
    margin-right: 0;
}
<div id="wrapper">
    <div class="red-box"></div>
    <div class="red-box"></div>
    <div class="red-box"></div>
    <div class="red-box"></div>
    <div class="red-box"></div>
    <div class="red-box"></div>
    <div class="red-box"></div>
</div>

查看更多
登录 后发表回答