Alain Jacomet Forte
Alain Jacomet Forte

Reputation: 4685

Switching DOM elements positions arbitrarily

I'm building a responsive website that changes widgets' position arbitrarily upon being viewed in different viewport widths.

Visually, its turning this:

big

Into this:

small

My first approach was setting placeholder div elements in this way:

<div data-change-from=".my-element"></div>

And using response.js to detect widths and move elements around with jQuery, but with complex grids and more widgets it has become unmanageable.

What is an efficient and reliable way to do this ?

Upvotes: 2

Views: 76

Answers (1)

bjb568
bjb568

Reputation: 11498

Use CSS

It's great and does all things.

body { position: relative }
body:after {
    content: '';
    display: block;
    clear: both;
}
#one, #two, #three, #four, #five, #six {
    height: 40px;
    background: #aaa;
    margin: 8px 1%;
    float: right;
}
#one-two {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 45%;
}
#one, #two { width: 100% }
#three, #four, #five, #six {
    float: left;
    width: 100%;
}
#five, #six { width: 50% }
@media screen and (min-width: 1000px) {
    #one-two {
        position: static;
        display: inline;
    }
    #one, #three, #five {
        width: 60%;
        float: left;
    }
    #two, #four, #six {
        width: 35%;
        float: right;
    }
}

Requires only one extra container:

<div id="one-two">
    <div id="two">2</div>
    <div id="one">1</div>
</div>
<div id="three">3</div>
<div id="four">4</div>
<div id="five">5</div>
<div id="six">6</div>

http://jsfiddle.net/nce9b/

Basically I have a default style that's applied unless overridden in the media query (min-width: 1000px). This rearranges the elements by adjusting floats, widths, and in the case of #one and #two applying position: absolute (to move it to the bottom). When the window is big enough, the media query overrides the styles forming a nice simple grid.

Upvotes: 1

Related Questions