Understanding the behavior of CSS float (even after thorough examination of W3C documentation)

I am currently facing an issue related to the float property and have provided a snippet of code below for reference. My goal is to achieve a two-column layout using floats. While I am familiar with other methods to achieve this layout, I am specifically interested in understanding the behavior of FLOAT in this scenario.

  • The container DIV contains two floated DIVs, both floated to the left.
  • As expected, the positioning of the second floated block element is determined by the size of the browser window.
  • The problem arises when the content inside the second floated DIV extends beyond a certain length, even with ample space available next to the first floated element.

In the code provided below, I have commented out a portion of the second paragraph. In my browser, I have observed that once the content reaches a certain point, the entire DIV clears the first one, even with space remaining in the second DIV.

Upon reviewing the code, I cannot identify any specific reason for this behavior. While I am aware of the general behavior of float with block-level and inline content, I have not found any documentation explaining this specific issue.

Any assistance would be greatly appreciated.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>CSS Float Problem</title>

<style>

body {
background:#5c604e;
}

#container {
position:relative;
background:yellow;
}

p {
background-color:#cccccc;
    width:50%;
}

.block {
width: 200px;
height: 200px;
}

.float {
 float: left;
}

.pink {
 background: #ee3e64;
}

.blue {
 background: #44accf;
}

</style>
</head>
<body>  
<div id="container">
<div class="block pink float">Lorem ipsum dolor sit amet consectetuer Nam fringilla Vestibulum massa nisl. Nulla adipiscing ut urna ipsum Curabitur urna lacinia pretium feugiat Ut. 
</div>   
<div class="blue float"> <h2>Test Heading</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum erat a neque eleifend vitae ultrices nisi tempor. Praesent facilisis lobortis nisl, <!--sit amet gravida orci mollis vitae. Maecenas porta turpis id urna porta id ornare velit dapibus. <!--    Proin sollicitudin, tortor viverra posuere mattis, nisl est rhoncus urna, nec elementum augue turpis vitae diam. Pellentesque ut quam sit amet elit tempus suscipit nec vel nulla. Proin ullamcorper sollicitudin metus in posuere. Aliquam a vehicula odio. Morbi scelerisque arcu ac nibh cursus ullamcorper. Aliquam pulvinar commodo nunc nec laoreet. -->  
    </p>
</div>
</div><!--end of container div --> 
</body>
</html>

View the code snippet at

Answer №1

In this scenario, you have positioned two block-level elements next to each other with a float property. Due to their block-level nature, they create a new context in which their contents will impact the layout.

When calculating the dimensions of floated elements, the standard approach is to base it on the content within the element. Since the second floated element lacks an explicit width, the browser determines that its width should be determined by its contents, which might result in it being as wide as feasibly possible.

Consequently, the second element appears below the first one because the paragraph's intrinsic width influences the blue box, making it larger than the designated constraints of its container (i.e., the width of #container minus the width of the first floated element).


If you desire the text to wrap around the floated element, you should eliminate the "blue" box. Only when the float and the content are within the same container (and the content isn't a block-level element) will the text flow around the pink box as expected.


For achieving a functional two-column layout with equal-height columns, consider using display: table if compatibility with IE7 is not a concern.

Answer №2

If you are trying to achieve a specific layout but are having issues with the width of the second block, consider setting a fixed width for it to prevent it from expanding uncontrollably based on content length.

You can try setting a fixed width for the first block and assigning the remaining width to the second block like this:

.block1 {
    width: 20%;
}

.block2 {
    width: 80%;
}

In your HTML code:

<div class="block1 pink float"> ..content.. </div><div class="block2 blue float"> ..whatever content.. </div>

Just make sure there is no space between the closing div tag of the left block and the opening div tag of the right block to avoid them being stacked on top of each other due to whitespace.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Properly Wrap Sub-Menu Elements in WordPress with Div Tags

I am currently working on styling my WordPress sub menu list items using HTML. I have written the HTML code that I want to use, but I am not sure how to incorporate it into the wp_nav_menu() function. Can you assist me with this? <ul class="menu"> ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...

What is the best way to download a modified canvas with filters using the solutions from stackoverflow?

There have been numerous inquiries regarding how to apply CSS filters to an image, with some solutions that don't utilize CSS filters but still achieve the desired outcome. However, for someone new to JavaScript like myself, these answers can be confu ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

"Selecting an element through Drag/Drop will result in the element being

INQUIRY I've encountered an issue with a draggable element ($("#draggable")) that interacts with a checkbox ($('#checkable')). When the $('#draggable') is dragged onto a box ($('#droppable')), it checks $(&apos ...

The Jquery function .load() doesn't load HTML comment tags as expected

Utilizing the .load() Jquery function enables me to insert html tags from one file into another. Here is an example of the code: <html> <head> <script src="jquery.js"></script> <script> function loadConte ...

What is the method for updating the color of the command bar in Fluent-React UI?

I'm working on some code and I'd like to change the background color while keeping the hovering effect. Can anyone help me with that? <CommandBar styles={{ root: { paddingLeft: 0, paddingRight: 0, selectors: { " ...

Having trouble with an AJAX request to display a template in Flask

Imagine having two radio buttons labeled 1 and 2, along with some text at the bottom of a webpage. Initially, the text value is set to -1 and no radio buttons are selected. If one of the radio buttons is clicked, the text value should change to either 1 or ...

Set the div element to be horizontally aligned

Is there a way to make this display horizontally instead of vertically, from left to right rather than top to bottom? I attempted using display:flex but only the extra-text class is affected and not the outer div. https://i.stack.imgur.com/2DNoC.png .m ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

How can I navigate and click on a drop-down menu link in Python using Selenium and CSS selectors?

This is an example of the HTML code: <span class="MenuIcons searchButton"></span> ... (additional content) <a data-bind="" url="/ParagonLS/Search/Property.mvc/Index/1" tabdescription="RESIDENTIAL" subtabdescription="Criteria" subtab ...

Link to xpath concept

I am trying to create a hyperlink to a particular spot on a website that I do not have access to edit. Unfortunately, there is no identifiable ID near the location I want to link to, so using <a href="http://example.com/page.html#location"> will no ...

"Clicking on a hash link will refresh the current page

I have a snippet of code embedded on external websites that loads HTML, CSS, and JavaScript using a <script> tag. Within the code is a JavaScript function that triggers when a specific link is clicked: <a href="#">?</a> If there are Ja ...

The v-btn label in Vuetify is extending beyond the lateral borders and overlapping

In this scenario, the button is supposed to break the line and increase its height. However, the text is overlapping the lateral borders (you can see this behavior in the Codepen link provided below). Is there a way to correct this issue? Codepen Link & ...

Can a class be created using a PHP variable as its basis?

Is it possible to define the body color based on a variable in PHP? I have been experimenting with different methods to achieve this. <?php $seperate_sitting_yes = "Yes"; if($seperate_sitting_yes == "Yes") { ?> <style type="text ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...

Using jQuery to toggle the menu

I've been brainstorming ways to add a toggle menu on my website and finally stumbled upon a solution that works great! http://jsfiddle.net/hhcsz5cr/ <div> <h1><button class="button" data-circle="travel"> <i cl ...

Utilizing HTML and CSS to Position Text Adjacent to the Initial and Final Elements in a Vertical List

Exploring a simple number scale ranging from 1 to 10, I experimented with different ways to represent it. Here's my attempt: <div class="rate-container"> <p class="first">Extremely Unlikely</p> <a class=" ...

What is the method for retrieving the active element with Waypoint?

Currently, I am implementing Waypoint (version 7.3.2) in my React project using React version 16. My goal is to create a scrollable list of items where each item fades out as it reaches the top of the container div. My main inquiry is how can I obtain a re ...

Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, wh ...