Set flex item width to 50%

My aim is to create 3 children with 50% width. By applying flex-wrap: wrap, the third child will go below the first one. However, I also want a 10px gap between the first and second child. Adding a margin-right: 5px to the first child and margin-left: 5px to the second child causes the second child to wrap underneath the first one due to insufficient space. To resolve this, you can utilize the Flexbox version and apply overflow: auto on the container to allow children that overflow to go below. Then, apply margin-right: 5px to the first child and margin-left: 5px to the two others.

Question:

To achieve my objective of having three children with 50% width, I plan to apply flex-wrap: wrap. This will make the third element appear below the first. Additionally, I want to create a 10px gap between the first and second children. However, when I try to add a margin-right: 5px to the first child and margin-left: 5px to the second child, the second one wraps underneath the first as there’s not enough space for it on the same line.

What is the percentage of the width occupied by 10px? I’m unsure how to calculate it.

.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;
}

s
s
s


Solution 1:

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;
}

s
s
s


Solution 2:


Utilize the flex attribute to determine the way a flex element will expand or contract to adjust to the available area in its flex box.

* {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;
}

s
s
s


Solution 3:

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;
}

1
2
3

Frequently Asked Questions

Posted in Css