Search code examples
csscss-floatmedia-queriesflexbox

Make fluid-sized block stick to top corner and allow content flow around it, but remain below content at certain breakpoints.


I've created a codepen to demonstrate the effect and what I want to achieve. It's not that complicated a problem, but I'm not sure how to be more concise and direct.

http://codepen.io/anon/pen/KwoeqR

What I want is to have a variable-width block of text that, when flowing normally, is below a block of content. But, through breakpoints and media queries, becomes stuck to the top right corner of the content, and allows the content to flow around it.

It's very easy to achieve one-half of the equation, or the other. I can achieve a floating top-right aligned block with this:

CSS:

.floater {
  float: right;
}

HTML:

<div class="floater"></div>
<p>A bunch of content text.</p>

But when, through a media query, the floater no longer floats, it sits above the content. It needs to sit below.

To make it sit below, I can just do this:

HTML:

<p>A bunch of content text.</p>
<div class="floater"></div>

But now it won't float properly - it does not stick to the top right corner.

Solutions I have tried:

  • Absolute positioning: This might work if the block were a fixed width. Instead it is a variable width so I can't simply set margins on the content.

  • Flexbox: A flex column reserves the space below it, instead of allowing other columns/content to flow into it. If there is a way to get a flex column to flow or float, that would work, but I have not found one.

I hope this makes sense. It sounds very particular and precise but it really is not. It's a simple layout problem that does not seem to have a simple answer, unless I am missing it!


Solution

  • You can use a combination of float, flex and media queries as below:

    .floater{
        float: right;
    }
    
    @media (max-width: 500px) {
        .wrapper{
            display: flex;
            flex-direction: column;
        }
        .main{
            order: 0;
        }
        .floater{
            order: 1;
        }  
    }
    

    http://jsfiddle.net/og8s0rvr/

    Here you can see that the floater is floated right until the window gets smaller than 500px. At that point it switches to a flex layout where the order of elements is changed via order.