9

So my goal is to have 3 children each with 50% width and use flex-wrap: wrap so that the third element goes beneat the first one, however, I also want to have a 10px gap between the first and second children elements and when I add a margin-right: 5px to the first child and margin-left: 5px to the second child, the second child wraps underneath the first one because the extra margin doesn't leave enough space for the second child on the same line.

How am I meant to figure out what % of the width are those 10px taking?

.projects {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.project {
    width: 50%
}
.project:nth-child(odd) {
    margin-right: 5px;
    background-color: red;
}
.project:nth-child(even) {
    margin-left: 5px;
    background-color: blue;
}
<div class='projects'>
   <div class='project'>s</div>
   <div class='project'>s</div>
   <div class='project'>s</div>
</div>
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • For the gap, you might want to use the CSS property `gap: 10px;` that works in modern browsers. – Flimm Feb 03 '22 at 09:58

3 Answers3

13

try this solution

.projects {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex-direction:row;
}
.project {
    flex:0 1 calc(50% - 10px);
    margin: 5px;
}
.project:nth-child(1) {
    background-color: green;
}
.project:nth-child(2) {
    background-color: red;
}
.project:nth-child(3) {
    background-color: blue;
}
<div class='projects'>
   <div class='project'>s</div>
   <div class='project'>s</div>
   <div class='project'>s</div>
</div>
Harry B
  • 2,864
  • 1
  • 24
  • 44
sbrrk
  • 896
  • 1
  • 7
  • 10
1

May be you can try

.projects {
    width: 100%;
    display: flex;
    flex: auto auto;
    flex-wrap: wrap;
}
.project {
    width: 50%;
    box-sizing: border-box;
}
.project:nth-child(odd) .m {

    background-color: red;
}
.project:nth-child(even) .m {
    background-color: blue;
}
.m {
    margin: 5px;
}
<div class='projects'>
   <div class='project'>
   <div class="m">1</div>
   </div>
   <div class='project'>
      <div class="m">2</div>
   </div>
   <div class='project'>
      <div class="m">3</div>
   </div>
</div>
Saleem
  • 1,059
  • 14
  • 27
1

Use the flex property to specify how a flex item will grow or shrink so as to fit the space available in its flex container.

* {box-sizing: border-box;}

.projects {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  width: 100%;
}
.projects > .project {
  flex: 0 0 calc(50% - 10px);
  margin: 5px;
}
.projects > .project:nth-child(odd) {
    background-color: red;
}
.projects > .project:nth-child(even) {
    background-color: blue;
}
<div class="projects">
   <div class="project">s</div>
   <div class="project">s</div>
   <div class="project">s</div>
</div>
Vishal
  • 268
  • 4
  • 3