开发者

How to let floating div span total width, if second div is empty?

I'm building a template which should accommodate two layouts:

I have a container with div A (left) and div B (right). A has always content. If B has content, it's width should be 30%, A gets the rest. Both colums should have 100% heigth, no floating around the shorter element.

If B is empty, it should not show at all and A should take up 100% width.

<div class="container">
  <div class="left">
    <placeholder 1 />
    <placeholder 2 />
  </div>
  <div class="right"><!-- can be empty -->
    <placeholder 3 />
    <placeh开发者_如何学Pythonolder 4 />  
  </div>
</div>

I would love to do this with just css. Is it possible? Or am I going to need to use javascript? IE6 is not an issue…


By default if B is without content, the div will be 100% of nothing, which makes it 0%; If there is content there, it will expand to the size of the content. But if you place a max width of 30%, you will have it go away with no content and have it max at 30%.

B.div {
    max-width:30%;
}


I tried accomplishing what I thought you meant with CSS only, but wasn't able to accomplish it. To achieve what I thought you needed, I had to add a little javascript.

Edit: Just remove the content from 'div B' and re-run the fiddle to see how it handles no content.

http://jsfiddle.net/QrNu7/21/


See: http://jsfiddle.net/3mDnr/

That works in IE8+ and all modern browsers.

It almost works in IE7 - the only problem is that the "empty right div" refuses to hide. There just isn't a pure CSS way to fix that, so I've included a snippet of jQuery-powered JavaScript to do it:

<!--[if lte IE 7]>
<script>
$(function() {
    $('.right:empty').hide();
});
</script>
<![endif]-->

You can use the faux columns technique to fake equal height columns.

HTML:

<div class="container">
    <div class="right">..</div>
    <div class="left">
        ..
    </div>
</div>

CSS:

.container {
    overflow: hidden
}
.left {
    overflow: hidden;
    background: #ccc;
}
.right {
    float: right;
    width: 30%;
    background: cyan
}


You should clear your floats - but this should be ok for handling the width issue you describe. Am I missing something?

 <div class="container">
      <div class="left">
        <placeholder 1 />
        <placeholder 2 />
      </div>
      <div class="right"><!-- can be empty -->
        <placeholder 3 />
        <placeholder 4 />  
      </div>
      <div class="clear"></div>
    </div>

in your stylesheet

.clear
{
clear:both;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜