Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make second div appear above first, without absolute position or changing html

Tags:

css

My page is split into 3 slices, as shown in this JFiddle.

In my full source code, I have media queries to help manage sizing between mobile and desktop. When someone accesses the site on mobile mode, Logo should appear at the top, and Items should appear below it. (I set display: none on my picture div to hide it)

Problem:

I can't change the positioning of the divs in HTML, or it'll disturb my current 3 slice layout. Absolute positioning is not an option, since most of my site is already dynamically sized, and I wouldn't want absolute positioning to interfere on a resolution I haven't tested on. This means calculating the margin sizes would be out of the question aswell.

So, absolute positioning is not allowed, nor is changing the orders of the divs. The result I'm looking for would be similar to this, exception without repositioning the divs.

My question is not about media queries, or how to size for mobile using media queries. I am only asking about how to get the layout I want with the restrictions in place (no absolute positing, no calculating margins, no changing div order).

Other questions I looked at:

Reposition div above preceding element - First answer suggests repositioning divs, which I cannot do. Second answer relies on calculating the position, which could interfere with other dynamically sizing elements.

Move The First Div Appear Under the Second One in CSS - Suggests I use absolute positioning, which I cannot do

like image 332
Vince Avatar asked Dec 09 '14 07:12

Vince


2 Answers

Flexbox layout is your friend here. display: flex can be used to interchange the elements position on the layout.

#container { display:flex; flex-direction: column; text-align:center;}
#items { order: 2 }
#logo { order: 1 }
#picture { display: none; }
<div id="container">
    <div id="items">Items</div>
    <div id="logo">Logo</div>
    <div id="picture">Picture</div>
</div>

display: flex works only in modern browsers. Check caniuse.

A test on my android mobile shows it working on Firefox and Chrome, but not on the stock Android browser.

like image 171
Alohci Avatar answered Nov 11 '22 07:11

Alohci


I tried to solve the solution using transform: translateY property in percentage value.

Note: This works if and only if the two containers have same height. or if the height is already known, then you can set the transform: translateY value according to the height.

CSS

@media (max-width: 700px) {
    #container > div {
        width: auto;
        display: block;
        float: none;
    }
    #container #picture {
        display: none;
    }
    #logo {
        transform: translateY(-100%);
    }
    #items {
        transform: translateY(100%);
    }
}

Working Fiddle

like image 2
Mr_Green Avatar answered Nov 11 '22 09:11

Mr_Green