Enabling horizontal scroll in flexbox

前端 未结 2 700
长情又很酷
长情又很酷 2020-12-13 18:00

I am new to flexbox, and I am trying to make a horizontal scrolling website. The idea is to show the first item as 100% height and width, like covering the screen with the r

相关标签:
2条回答
  • 2020-12-13 18:31

    Flex items have "flex-shrink: 1" by default. If you want the first item to fill the container and force the others to overflow (as it sounds like you do), then you need to set "flex-shrink: 0" on it.

    The best way to do this is via the "flex" shorthand, which you're already using to give it "flex: 10".

    Just replace that with flex: 10 0 auto -- the '0' there gives it a flex-shrink of 0, which prevents it from shrinking below the width:100% that you've given it.

    Perhaps better: just give it flex: none, since I don't think you're really getting any benefit from the "10" there, since there's no free space to distribute anyway, so the "10" is giving you 10 useless shares of nothing.

    So that makes your 'splash' rule into this:

    .splash {
        background-image: url(1.jpg);
        width:100%;
        background-size:cover;
        background-position:50% 50%;
        background-repeat: no-repeat;
        transition: all 0.6s ease;
        flex:none;
    }
    

    Here's a fiddle with this change (but otherwise using your provided CSS/HTML). This renders like your mock-up in Firefox Nightly and Chrome: http://jsfiddle.net/EVAXW/

    0 讨论(0)
  • 2020-12-13 18:35

    I think I got a better way - especially when you're creating a horizontal scrolling carousel:

    .container {
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      overflow-x: auto;
    }
    
    .item {
    /* how you style this doesn't really matter - depends on your requirements -
       but essentially you want the items to span full width, and that's the 
       default (every flex container item has flex-grow set to 1)
    */
    }
    

    Take not here: I changed the direction to column so that flex-wrap now wraps horizontally. Also, you can change overflow-x to hidden if you don't want the scrollbar to show - but don't omit the overflow-x property since that means it will be the outter parent to now overflow (something I wouldn't find desirable)

    The JS can then kick in.

    Cheers

    0 讨论(0)
提交回复
热议问题