Home > OS >  flex css - clip elements after certain height instead of wrapping
flex css - clip elements after certain height instead of wrapping

Time:12-28

flex default behavior

The border represents the static heights and widths.

I want Item five and item six to stay in the second row and have item three and six clipped instead of wrapping the third time as shown in the picture. How can I achieve this through flex?

I want the outcome to look like this for visualization:

[enter image description here]

https://codepen.io/akeni/pen/LYBGOXB

<div id="example-element"  style="flex-wrap: wrap;">
        <div>Item One</div>
        <div>Item Two</div>
        <div>Item Three</div>
        <div>Item Four</div>
        <div>Item Five</div>
        <div>Item Six</div>
</div>


#example-element {
    border: 1px solid #c5c5c5;
    width: 300px;
    height: 150px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
}

#example-element > div {
    background-color: rgba(0,0,255,.2);
    border: 3px solid #00f;
    width: 60px;
    margin: 10px;
}

CodePudding user response:

Its a little bit confusing calling a flex container "element". I personally prefer to call them "blabla-container", where 'blabla' is waterver I'm working with in that section (for example: "nav-links-container". But that of course is just a matter of taste.

About the question, thanks for the new info, if you are open to suggestions, the easiest way to do it is with css-grid:


#example-element {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    /* or this way: 
    grid-template-columns: auto auto auto;
    */   
    overflow-x: hidden !important;
}

You can find more detailed info here: MDN Docs, css-grid

Ahh and one more detail, what you call "clipping", happens when the parent container is not big enought to contain the children with fixed sizes, so if after applying this changes you don't see it behaving as in the second picture, simply make the parent component smaller (200px for example) and voila!

CodePudding user response:

Grid layout would be easier here, as you want to show specific numbers of columns per row.

Use grid-template-columns to specify how many columns you want and their width. Then use overflow: hidden to hide those overflowed elements.

#example-element {
    border: 1px solid black;
    width: 300px;
    height: 150px;
    display: grid;
    grid-template-columns: repeat(3, 100px);
    gap: 1rem;
    overflow-x: hidden;
}

#example-element > div {
    background-color: rgba(0,0,255,.2);
    border: 3px solid #00f;
    width: 100px;
}
<div id="example-element"  style="flex-wrap: wrap;">
        <div>Item One</div>
        <div>Item Two</div>
        <div>Item Three</div>
        <div>Item Four</div>
        <div>Item Five</div>
        <div>Item Six</div>
</div>

  • Related