Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox with percent width but fixed margins

Tags:

css

flexbox

I'm trying to switch from a CSS grid framework to a flex layout (because of different items height, and flexbox handles that very nicely).

So, this is what I did: http://jsfiddle.net/c3FL2/

.container {
    display: flex;
    flex-wrap: wrap;
    padding: 15px;
    background: #9999FF;
}
.g {
    background: #FF9999;
    border: 1px solid red;
    border-radius: 8px;
    padding: 15px;
}
.grid-33 {
    width: 33.3333%;
}
.grid-50 {
    width: 50%;
}
.grid-66 {
    width: 66.6666%;
}
.grid-100 {
    width: 100%;
}

My question is: how can i add a margin between flex items? I want exactly 15px, not a percentage. If I add that, it breaks the layout because of too much width. Padding is not a solution because I want a border outside elements.

The solution doesn't have to be compatible with old browser, just the latest ones since this will be running on a controlled environment.

Edit: If needed, the HTML can be changed.

like image 578
JohnKiller Avatar asked Sep 12 '25 07:09

JohnKiller


2 Answers

The "easiest" way to do this is to use calc(). (It would of course be easier if you didn't have to solve for IE quirks to get there, but the end result is very straightforward.) Your code would look like this:

.container {
  padding: 15px 15px 0 0;
}
.g {
  margin: 0 0 15px 15px;
}
.grid-33 {
  with: calc(33.3333% - 15px);
}
.grid-50 {
  width: calc(50% - 15px);
}
.grid-66 {
  width: calc(66.6666% - 15px);
}
.grid-100 {
  width: calc(100% - 15px); // needed for IE10
}

The reason for using width is because IE10-11 aren't great fans of calc being used together with flex. In this case it's a box-sizing: border-box issue. This example is cross-browser compatible with IE10+.

Demo

(To see vendor prefixes, click "View Compiled" in CSS.)

like image 179
sam Avatar answered Sep 13 '25 21:09

sam


You might try : background-clip and box-shadow and transparent borders: DEMO

    .g {
        background: #FF9999;
        border: 8px solid transparent;/* you may tune individually border-size to get your 15px */
        box-shadow:inset 0 0 0 1px red;/* this will fake your border if set with out blur */
        background-clip:padding-box;/* do not show bgcolor under borders */
        border-radius: 15px;/* increase value so it has effect deeper seen  on inset box-shadow */
        padding: 15px;
    }
like image 35
G-Cyrillus Avatar answered Sep 13 '25 22:09

G-Cyrillus