Using Overflow in CSS

Overflow can really help you when you have content that wants to go past the boundaries of your divs. By default, Overflow is set to visible, so if your content goes past the boundaries that you have set for your content area, Overflow can help to remedy the problem. In the example, I have set up a container with a sidebar and a content area. In the content area, the text is lengthy and goes past the visible layout and runs into the body of the site. This can be a pain if you absolutely have to have certain content in a designated spot, but don’t want to break the layout.

The HTML

<body>  
   <div id="container">
      <div id="sidebar">
         <p>Lorem ...</p>
         <p>Aenean ...</p>
         <p>Nulla ... </p>
      </div>
      <div id="content"></div>
   </div>
</body>  

I shortened the text above, just so you wouldn’t have to scroll through it, but you can imagine a massive amount of text where I have placed 3 dots. I set up the CSS so that each section would have a designated size, so that you can see how the text acts when it runs out of room.

#container {
    margin:auto;
    background:#FFF;
    width:960px;
    height:600px;
}
#sidebar {
    background:#CCC;
    width:360px;
    height:600px;
    float:left;
    overflow:visible;
}
#content {
    background:#303;
    width:600px;
    height:600px;
    float:right;
}

The sidebar is 360px wide and 600px high. Once the text reaches the bottom bounds, it runs past the boundaries and possibly over other content. If you want the content to stop when it reaches the bottom boundary of the sidebar, simple set the overflow property to hidden, as in the code below:

#sidebar {
    background:#CCC;
    width:360px;
    height:600px;
    float:left;
    overflow:hidden;
}

As you can see, the text stops directly where the boundary of the sidebar is located. The problem is that it cuts off the text and you can’t read it all. Also, it cuts the last line off in the middle. This isn’t good, but we can fix it to where the content is within the boundaries, and we can view it all as well. We simply set the Overflow Property to Scroll, as in the code below:

#sidebar {
    background:#CCC;
    width:360px;
    height:600px;
    float:left;
    overflow:scroll;
}

As you can see from the example, the scroll style creates a scroll bar on the side, so that the entire content is accessible, while still remaining within the confines of the div. If you have a mouse with a scroll wheel, if you hover your mouse over that content area and use the scroll wheel, it will scroll the content.