Few common problems when working with Flexbox

Tram Ho

When it comes to UI, what is the solution for the even spacing between the elements, as well as the elements that are always equal even though the content changes?

Problem 1: For the same high columns, in Flexbox when using display: flex , the default value flex-direction: row and align-items: stretch , the stretch value makes direct children of the parent tag use display : flex is always the same height. Note that according to flex-direction: row and flex-wrap: nowrap, if using wrap, an element falls into a new row and it will compare with the other elements in its row, no matter how high. it does not affect the height of the other row elements.

Problem 2: When dividing the layout with only 3 elements as shown, use justify-content: space-between then determine the distance between each element, here we have 30px, we have 3 columns from that distance at the middle will be 30 × 2 = 60px then divide by 3 columns = 20px . From there we can CSS the width of the elements is width: calc(33.333% - 20px) the result will be exactly as Design.

Problem 3: Same layout as above but only 5 elements, when using space-between , with flex-wrap: wrap , elements 4 and 5 will be in line, but element 5 will be at the end of the bad layout. The solution is to justify-content default value of flex-start, but the elements will stick together.

From here we have another solution that we know the distance between elements is 30px , deduce each side of the element will take up 15px of space, we can use margin: 0 15px for those elements, resulting suitable for width: calc(33.333% - 30px) , -30px because when using margin on both sides 15px it pushes out. But the first element will be squeezed because of margin-left as well as margin-right with the last element, from here we can CSS for the negative margin parent class is margin: 0 -15px to push back, this is quite familiar if use Bootstrap in classes on columns or use this.

If you want to optimize more easily scalable, then you can use variables in CSS with a variable such as --gutter: 15px for example, this time the code of the child elements such as image__item go ha will be width: calc(33.33% - calc(var(--gutter) * 2)); margin: 0 var(--gutter); and the parent, for example, image__list would be margin: 0 calc(-1 * var(--gutter)); Now suppose you want the distance between them to be 60px away, you just need to change the value at –gutter to 30px instead of 15px to be delicious.

Above are some tips of myself hoping to help you. I wish you good learning, improve your level.

Share the news now

Source : Viblo