Expand div to max width when float:left is set

Hope I've understood you correctly, take a look at this: http://jsfiddle.net/EAEKc/

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Content with Menu</title>
  <style>
    .content .left {
      float: left;
      width: 100px;
      background-color: green;
    }
    
    .content .right {
      margin-left: 100px;
      background-color: red;
    }
  </style>
</head>

<body>
  <div class="content">
    <div class="left">
      <p>Hi, Flo!</p>
    </div>
    <div class="right">
      <p>is</p>
      <p>this</p>
      <p>what</p>
      <p>you are looking for?</p>
    </div>
  </div>
</body>

</html>


The most cross-compatible way I've found of doing this is not very obvious. You need to remove the float from the second column, and apply overflow:hidden to it. Although this would seem to be hiding any content that goes outside of the div, it actually forces the div to stay within its parent.

Using your code, this is an example of how it could be done:

<div style="width: 100px; float: left;">menu</div>
<div style="overflow: hidden;">content</div>

Hope this is useful to anyone having this issue, it's what I found works the best for the site I was building, after trying to get it to adjust to other resolutions. Unfortunately, this doesn't to work if you include a right-floated div after the content as well, if anyone knows a good way to get that to work, with good IE compatibility, I'd be very happy to hear it.

New, better option using display: flex;

Now that the Flexbox model is fairly widely implemented, I'd actually recommend using it instead, since it allows much more flexibility with the layout. Here's a simple two-column like the original:

<div style="display: flex;">
    <div style="width: 100px;">menu</div>
    <div style="flex: 1;">content</div>
</div>

And here's a three-column with a flexible-width center column!

<div style="display: flex;">
    <div style="width: 100px;">menu</div>
    <div style="flex:1;">content</div>
    <div style="width: 100px;">sidebar</div>
</div>

Solution without fixing size on your margin

.content .right{
    overflow: auto; 
    background-color: red;
}

+1 for Merkuro, but if the size of the float changes your fixed margin will fail. If u use above CSS on the right div it will nicely change size with changing size on the left float. It is a bit more flexible like that. Check the fiddle here: http://jsfiddle.net/9ZHBK/144/

Tags:

Html

Width