Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not use <div class="clear"> in markup

Tags:

css

xhtml

All the time my code is riddled with <div>'s that are used to clear/expand a div to look correct. Whenever it doesn't look correct, I add a <div style="clear:both;"> and it fixes the problem in IE7.

How do I avoid doing this? I mess with the overflow:auto, overflow:hidden and I get nothing.

Thanks in advance

like image 766
Tom Avatar asked Jul 13 '11 15:07

Tom


People also ask

How do I make sure text stays inside a div?

You can force the content of the HTML <div> element stay on the same line by using a little CSS. Use the overflow property, as well as the white-space property set to “nowrap”.

What is div style clear both?

The “clear: both” means floating the elements are not allowed to float on both sides. It is used when no need of any element float on the left and right side as related to the specified element and wanted the next element only shown below.

How do you stop a div?

Divs can't be disabled. Only form and form elems. Actually in Quirks-mode IE can disable a div , but it only grays button texts, it doesn't prevent events firing.

Do you need to close a div?

Div tag has both open(<div>) and closing (</div>) tag and it is mandatory to close the tag.


2 Answers

One common method is the clearfix class. Instead of needing extraneous <div style="clear:both;"> elements (as you have been doing) after the floating element, you simply add this class to the floating element itself and the layout is automatically cleared after it.1

My favorite one is from http://perishablepress.com/press/2009/12/06/new-clearfix-hack. It supports modern browsers as well as IE6 and IE7.

/* new clearfix */
.clearfix:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;
    }
* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

Example (old/bad):

<div class="floatingrightmenu">This floats right</div>
<div style="clear:both;"></div>
<p>This text is cleared below it.</p>

Example (new with clearfix):

<div class="floatingrightmenu clearfix">This floats right</div>
<p>This text is cleared below it.</p>

1: Note: the automatic clearing means that it works best with single floated elements. If you wish to have multiple elements floated next to each other, put them all into a single container which is also floated and apply clearfix to that container.

like image 157
Nicole Avatar answered Sep 17 '22 16:09

Nicole


if you pop overflow:hidden; on the container of the floating elements that should work! dunno how cross browser it is however.

like image 43
Treemonkey Avatar answered Sep 21 '22 16:09

Treemonkey