Change order of floated divs with CSS

后端 未结 4 510
孤城傲影
孤城傲影 2020-12-16 15:07

JSFIDDLE

I want to change the order of floated divs at a certain pixel size.

At default state they both have 50% width and they are next to

4条回答
  •  無奈伤痛
    2020-12-16 15:48

    I know that you're asking how to accomplish this utilising floats, but as far as I know using pure CSS this is impossible (at least without using nasty positioning, which you've said you don't want to do).

    As far as I know the only nice way to accomplish this with pure HTML/CSS is to utilise the new flexbox spec (a good starting point would probably be this css tricks article).

    When you use flexbox you can use the order property on items to dictate which order items appear in (duh)

    You can see an example of this in action here, the HTML code is similar to what you have, with an added wrapper element (I also fixed the DOCTYPE declaration):

    
    

    The CSS is a little different:

    .wrapper {
      display: flex;
      flex-flow: row wrap;
    }
    
    .yellow {
        background: yellow;
        width: 20%;
        height: 300px;
    }
    
    .red {
        background: red;
        width: 20%;
        height: 300px;
    }
    
    @media screen and (max-width:600px) {
        .yellow {
            order: 2;
            width: 100%;
        }
    
        .red {
            order: 1;
            width: 100%;
        }
    }
    

    I've also cleaned it up a little, you had duplicate code in your media query which didn't really need to be there.

    The only downside to this is that it currently only works on around 80% of browsers as of writing:

    http://caniuse.com/#search=flexbox

    Depending on your target market that might be OK, you could use graceful degradation so that it appears correctly in all ways except the ordering on devices that don't support flexbox fully.

    I guess you're also only really targeting mobile devices with reordering things, support there is good so it might work well for you.

提交回复
热议问题