开发者

Transposing div elements using CSS

I'll jump to an example.

开发者_开发百科<!DOCTYPE html>
    <head>
        <title>Transposing div using CSS</title>

        <style>
            div#wrapper {
            }

            div#menu {
                border:blue solid 1px;
            }

            div#main {
                border:red solid 1px;
            }
        </style>
    </head>

    <body>
        <p>How do we show the menu div immediately after the content div?</p>
        <div id="wrapper">
            <div id="menu">Menu</div>
            <div id="main">Content</div>
        </div>
    </body>
</html>

In a browser, the menu div will come first in the flow. Now let's say that I need to change the layout so that "Menu" follows the content div content. How can this be done using CSS only. That means no change to HTML (no user agent detection stuff) and no JavaScript code.

The main CSS technique to position elements is to use the float:right|left attribute. It works well to move elements with respect to their bounding box, but I'm looking at moving an element at the end of its successor element in the normal flow.

And here's the use case. I want a web site to show up optimally on small screen browsers like on an iPhone. The web site currently has the menu at the top and content below, a very common layout but on an iPhone, the real estate is so limited that it would be preferable to have the menu following the main text content.

The solution only has to work with iPhone and Android mobiles (WebKit-based). So no need for taking into account Internet Explorer hacks and such.


If your menu has a fixed height (which most likely it does) you could use the same principles as the sticky footer: apply position relative on the wrapper, and a bottom padding of the same height as the menu. In code:

div#wrapper {
    height: 100%;
    padding-bottom: 100px;
    position: relative;
}

div#menu {
    border:blue solid 1px;
    position: absolute;
    bottom: -2px; /*to offset the border pxs*/
    height: 100px;
    width: 100%;  
}

div#main {
    border:red solid 1px;
}

You can view it in action here: http://jsfiddle.net/3ZheQ/


I haven't tried this on mobile phones yet, but I often did this on regular sites. I usually did it so that I wrapped both .menu and .menu_section into the .header div. Then you set some basic margin-top to the .menu div and add position:relative to the .header. Now header is your last relative for .menu and .menu_section.

Now just set position:absolute to the .menu_section, and you can set the top margin to 0. The .menu is going to be offset by the top margin while the .menu_section will be absolutely positioned at top of header.

If the design requires it, you can solve any overlapping with z-indexes (but you're not working for Internet Explorer oldies anyway, so that probably won't bother you).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜