开发者

Position an element relative to an ancestor or earlier sibling

开发者 https://www.devze.com 2023-04-04 07:39 出处:网络
I had the following code which gave me my desired appearance, but I always felt the document order was incorrect, as the sidebar should come later:

I had the following code which gave me my desired appearance, but I always felt the document order was incorrect, as the sidebar should come later:

<h1>header</h1>
<div style="float:right">variable height sidebar</div>
variable height content
<h2>sub-section</h2>

The sidebar, on desktops, may extend into the following section, which is fine. I would rather have that than a big white space (i.e. the h2 does not clear:right).

On mobile platforms however, I wanted to linearise the sidebar, and for it to come after the content. Therefore I had to change the document order, and get it looking as I had it before. Obviously, I could do this:

<h1>header</h1>
<div style="overflow:auto">
    <div style="float:left">variable height content</div>
    variable height sidebar
</div>
<h2>sub-section</h2>

And leave a big gap below the content, if it is short. But I was wondering if it was possible to keep the content "unfloated", yet still position the sidebar under the h2 element on开发者_如何学运维 desktops.

The earliest browser I care about is IE7. I do not want a JavaScript solution. I have tried negative top margins and I have tried absolute inside relative positioning, with a wrapper element, but neither gave a good solution. To summarise: I want the sidebar to come second in document order; on desktops, I want the h2 to clear the content but not the sidebar, and the sidebar to be in the top-right just under the h1; on mobiles I want the content and sidebar both in flow.

Is this possible?


As I understood the task, you need something like this: http://jsfiddle.net/kizu/yDx9G/

And if you'll need the sidebar to be at the bottom of everything, and if you're targeting only modern mobile platforms, you can try to change vertical the order of the elements using the flexbox or table behavior in the media queries.

There are two great articles about this issue on adactio.com:

  1. Article about flexbox
  2. Article about using display:table for changing order of elements


Have you considered wrapping the content in containers? For example:

<div id="content">
  <h1>Header</h1>
  <h2>sub-section</h2>
</div>

<div id="sidebar">
  variable height sidebar
</div>

You could then use CSS positioning to place them anywhere you want. A really simple version:

#content {
  float: left;
}

#sidebar {
  float: right;
}

As seen here.

0

精彩评论

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

关注公众号