Why was the element with id=box-2 displayed outside of its designated box? Exploring the overlapping rule of floats in CSS

The stylesheet code is

#box {
    width:400px;
        height:200px;
        border:1px solid black;
}
#box-1 {
    width:100px;
    height:100px;
    background-color:red;
    float:left;
}
#box-2 {
    width:100px;
    height:100px;
    background-color:yellow;
}
</style>
</head>

<body>
<div id="box">
  <div id="box-1">id=box-1</div>
  <div id="box-2">id=box-2</div>
</div>
</body>

https://i.sstatic.net/eSbzj.png

It is observed that box-2 was overlapped by box-1.
The issues that confuse me are:
1. Box-1 was placed inside the box before box-2, so why did box-2 not overlap box-1?

https://i.sstatic.net/eOG5g.png

2. Why was the text id=box-2 not within box-2?
If box-2 was indeed overlapped by box-1 and the text id=box-2 was inside box-2, the result would look like this:

https://i.sstatic.net/3ry4F.png

Please explain the principles of the CSS float rule.

Answer №1

Using floats solely for element positioning, not layout construction, is essential. Many users face issues with understanding this concept.

The fundamental principle of CSS floats is that the floated element exits the regular flow. Consequently, when an element is floated, the line-height at its position becomes zero. To illustrate this point, consider the following example:

.box {
  position: relative;
  border: 2px solid red;
  clear:both;
  margin-bottom: 40px;
}
.floated {
  float:left;
}
.box > div {
  border: 1px solid blue;
}
<div class="box">
  <div class="floated">Floated div</div>
</div>

<div class="box">
  <div>Not Floated div</div>
</div>

In the provided example, the red border represents the line height. It is evident that the content within .floated extends beyond the boundaries of the container .box, rendering the box seemingly empty without any visible content due to its zero height. Moreover, the use of .box is necessary to prevent conflicts.

Let's examine another instance. Floats are commonly used for creating grids, although I personally discourage this technique. Here is a typical procedure involving floats:

.grid {
  position: relative;
  width: 400px;
}

.grid.floated .element {
  float: left;
  width: 32%;
  border: 1px solid blue;
}
.grid.inline-block {
  font-size: 0;
}
.grid.inline-block .element {
  display: inline-block;
  vertical-align: top;
  font-size: 1rem;
  width: 32%;
  border: 1px solid blue;
}

.clear {
  clear: both;
}
<h1>Floated grid</h1>
<div class="grid floated">
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element with different height and content</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
</div>
<div class="clear"></div>
<h1>Inline block grid</h1>

<div class="grid inline-block">
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
  <div class="element">Element with different height and content</div>
  <div class="element">Element</div>
  <div class="element">Element</div>
</div>

The problem arises with floated grids when elements vary in height, leading to stacking issues. Clearing floats post usage is imperative.

An alternative approach is the inline-block grid which sidesteps the complications encountered with floated grids. This method ensures correct line heights, maintains proper element order within the document flow, and eliminates the need for clearing floats.

Common Issues Associated with Floats

Initiating a layout using floats necessitates floating subsequent elements or consistent clearing. Additionally, floated elements transition into block elements, altering their original inline nature. An illustration would be converting a <span> (inline element) into a block element akin to a <div> within the layer stack (consisting of floats, absolute positioning, opacities, etc.), thus presenting challenges if one fails to grasp float behavior accurately.

Conclusions and Recommendations

While floats serve as effective tools for positioning individual elements like images alongside text, they have become somewhat obsolete amidst the availability of modern layout techniques such as flexbox and inline-block elements. Consequently, it is advisable to explore alternative methods (e.g., positions, displays, flexbox, inline-block elements) for constructing layouts instead of relying heavily on floats, reserving their use primarily for positioning singular elements.

Best of luck!

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

What is the true functionality of the Bootstrap Grid system?

I am currently in the process of grasping how this functions. As an example, I have created columns and inserted <hr> for visualization purposes. This is what I have attempted thus far: I adjusted the row's margin to be -15px on both sides. C ...

Tips for changing between two texts within a button when clicked

Seeking a solution for toggling between two different texts inside a button when making an ajax call, with only one text displayed at a time. I'm facing difficulty in targeting the spans within the button specifically. Using 'this' as conte ...

Large header picture

Instead of tiptoeing around the issue, let me just be blunt and ask: I'm curious about how they created this image header. Even after removing all javascript code and css using Chrome's property inspector, the image continued to stretch. The sty ...

Styling Your HTML Background with CSS and Enhancing it with JavaScript

I am lost when it comes to understanding the design of I have spent hours researching how to create backgrounds using shapes and css, but I haven't been successful. Can someone please help me figure out how to create a background similar to . Thank ...

When implementing the navbar-fixed feature in Materialize, I've noticed that my icon disappears

Why does my icon disappear when using navbar-fixed with materialize, but not when I use the fixed navbar? Icon with regular navbar: https://i.sstatic.net/Z5XEl.png Icon with navbar-fixed: https://i.sstatic.net/HHgWv.png ...

Sign in with AJAX technology

Greetings and thank you in advance! This is my first question on this platform. I am currently working on a PHP login script, and my code is nearly complete. Below is a snippet of the code: HTML FORM <input type="text" id="username" /> <input ty ...

What methods can be used to crop and style images in a similar manner using html and css?

Is there a way to replicate this specific method? I attempted to achieve the same look by using CSS masking, but the results weren't pleasing. Does anyone have suggestions on how to accomplish this using HTML/CSS? ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: https://i.sstatic.net/LURG3.png I am ...

The Wordpress theme is malfunctioning when accessed on the internet

After successfully installing WordPress and a theme, customizing it on my localhost, everything appears to be working fine on the PC where XAMPP is installed. However, when attempting to access the same page from another PC on the network, there seems to ...

What is the method for altering the "return" of a CSS transition?

Today, I delved into the world of transitions and I must say, they are amazing and have great potential for future websites. Take a look at my current code: http://jsfiddle.net/Ldyyyf6n/ I am looking to tweak the "return" transition of the circle/square ...

Innovative Audio Editing Tool using Javascript

Currently, I am in the process of creating a JavaScript-based audio editor that will allow users to record, play, and edit audio files. It is crucial for the tool to be able to visualize both real-time recorded audio and selected/uploaded audio files. Whil ...

Why is it so difficult for me to move it to the next line?

p { font-size: 150%; } body { background-image: url("images/gg.jpg"); background-repeat: repeat; } .rTable { display: block; margin-top: 100px; margin-bottom: 200px; margin-right: 200px; margin-left: 450px; } .rTableHeading, .rTableBody, ...

Zooming Fluidity

These are my specifications: Font size should adjust fluidly from 14px to 22px between 1280 and 1920 Users must be able to zoom normally Finding a solution that accomplishes both has been challenging. I've explored CSS Tricks simplified fluid approa ...

What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue: I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication ...

How can the Multi-tiered Dropdown Menu be Enhanced?

I am in search of creating a multi-level accordion menu. I have developed this menu ( http://codepen.io/anon/pen/ogdovx ) until now but I am fairly new to jquery and feeling stuck when it comes to advancing it further. How can I enhance this? My requireme ...

During the Internet Explorer browser, the command will run two times

<div style="width:expression(alert('1'));"></div> When this code is executed in IE7, it will trigger the alert function twice. Why does this happen? ...

Ways to restrict users from accessing a file stored on the server?

This might seem like a silly question, and yes, it is quite naive. I currently have two files stored on my server: index.html, file.txt Is there a simple way to prevent users from accessing file.txt directly by entering its URL like this: website.d ...

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Show a div depending on a certain condition, such as whether there are children present in a ul

Can you please review the code snippet below? I am trying to make it so that the #non-alphabet element is displayed only if there are no child elements (brand-options) within .refinement-options. How can this be achieved? *For further clarification, refer ...