What is causing the floated element to overlap the element below instead of vice versa?

div {
  background-color: #00FFFF;

}
p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin: 0px;

}

#p1 {
  background-color: red;
float: left;


}
#p2 {
  background-color: green;
}
#p3 {
  background-color: orange;
}
#p4 {
  background-color: yellow;
}

span {
  position: relative;
}

#s1 {
 top: 1px;
 left: 1px;
}

#s2 {
  top: 2px;
 left: 2px;

}
#s3 {
  top: 3px;
 left: 3px;

}
#s4 {
  top: 4px;
 left: 4px;

}
<h1>Floating Elements</h1>

<div>
  <p id="p1"><span id="s1">A</span></p>
  <p id="p2"><span id="s2">B</span></p>
  <p id="p3"><span id="s3">C</span></p>
  <p id="p4"><span id="s4">D</span></p>
  <section>This is regular content continuing after the the paragraph boxes.</section>
</div>

Answer №1

Curious why?

The reason lies in the behavior of the float property.

Applying the float property to an element doesn't dictate how that specific element should be displayed, but rather influences the flow of content around it.

Specifically, this affects inline content following the floated element.

Since your paragraphs are block elements with fixed dimensions (50px width and height), the visible outcome is as follows: the inline content of paragraph #p2 wraps around paragraph #p1, but the constraints on the parent element prevent it from expanding accordingly.


Edit:
If you're struggling to grasp the concept, consider a simplified example:

#floated {
  float:left;
  width: 50px;
  height: 50px;
  border:1px solid red;
}

#unfloated {
  border:1px solid blue;
  background: green;
}
<div id="floated"></div>

<div id="unfloated">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</div>

As evidenced above, without a background for the floated element, the non-floated div stretches underneath it, allowing only its inline content - the Lorem Ipsum text - to wrap around the floated element.

This exemplifies the essence of how float works.

In your scenario, the appearance of "B" inside the second square occurs because the parent block element restricts the width and height to 50px, preventing it from enclosing "B"; thus, the text overflows the parent element boundaries due to the default overflow:visible.

Answer №2

According to MDN's explanation on Stacking and float

When dealing with floating blocks, the stacking order differs slightly. Floating blocks are positioned between non-positioned blocks and positioned blocks.

Furthermore, it mentions

In cases where the opacity of the non-positioned block (#p2 in your scenario) is decreased, a peculiar behavior occurs: the background and border of that block appear above the floating blocks but still remain beneath positioned blocks.

Answer №3

To ensure proper alignment of floated elements, it is recommended to include a clear-fix like so:

When dealing with floated elements, adjacent elements tend to wrap around them. To prevent this behavior, the clear property can be used.

Learn more about CSS Layout - float and clear

div {
  background-color: #00FFFF;

}
p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin: 0px;

}

#p1 {
  background-color: red;
float: left;


}
#p2 {
  background-color: green;
}
#p3 {
  background-color: orange;
}
#p4 {
  background-color: yellow;
}

span {
  position: relative;
}

#s1 {
 top: 1px;
 left: 1px;
}

#s2 {
  top: 2px;
 left: 2px;

}
#s3 {
  top: 3px;
 left: 3px;

}
#s4 {
  top: 4px;
 left: 4px;

}

.clear { clear:both; }
<h1>Floating Elements</h1>

<div>
  <p id="p1"><span id="s1">A</span></p>
  <div class="clear"></div>
  <p id="p2"><span id="s2">B</span></p>
  <p id="p3"><span id="s3">C</span></p>
  <p id="p4"><span id="s4">D</span></p>
  <section>This is regular content continuing after the the paragraph boxes.</section>
</div>

Answer №4

Remove the float: left; property from #p1{}, instead add a position:relative; to your div{} and include position: absolute; top: 0; left: 0; for your #p2{}. It's unclear what your goal is, but if you prefer to retain the float: left; on #p1{}, then you must apply clear: both; on p{}.

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

Hide Scrollbar in CSS

Looking for a way to conceal the vertical scrollbar on my website, especially on mobile devices with touch scrolling capabilities. I attempted using CSS but didn't get satisfactory results, especially on older browser versions. ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...

Explore the versatility of jQuery by utilizing multiple objects in your POST and GET requests to PHP for enhanced

I am trying to send multiple arrays to a PHP page using jQuery and retrieve results, but I am encountering an issue where the array values are not being properly passed to the PHP page. Notice: Undefined index: $name Notice: Undefined index: $type Notice ...

How to display an image in a pop-up with a title

I am currently using the Bootstrap framework and I am trying to create a popup image with a title, but it only shows the image. I am not sure how to add code in JavaScript to display the title as well. Can someone please assist me? Here is my code: Javas ...

Developing a new class within a function

In this section of the HTML file, I have set up a form to collect email and password information from new users in order to create a new profile: <form name="userInfo"> <fieldset> <legend>Create a new account</legend> ...

Utilizing a jQuery plugin for input file validation

This code is functioning properly, however the file field is not being validated. All input fields are successfully validated by this plugin except for the file type field. I believe there may be something missing in my implementation, so please help me de ...

What is the best way to conceal the bottom portion of an image?

My image in the header overlaps with the next section's features (image-phone). I've tried changing the position and z-index types. If I crop the image, it's not ideal and difficult to fix ;) How can I structure my image: using a div-class ...

The o-gradient feature is not compatible with Mac and Linux operating systems

Hello there! I am facing an issue with creating a gradient on my website without using an image. Surprisingly, the gradient appears on Windows but not on Mac or Linux operating systems. Any idea why this might be happening? You can check out the website he ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

What method is most effective for comparing two HTML pages that contain identical content but varied markup?

I'm in search of a method to analyze two HTML pages for content. Both pages were created with React, but they have different structures. Nevertheless, the text within these pages is identical. What would be the most effective approach for comparing th ...

What is the reason that elements with % properties totaling 100% do not align next to each other?

I've been attempting to arrange two blocks side by side within another block, but they just don't seem to fit together smoothly. What could be causing this issue? .container {height: 200px; width: 400px; background:darkgrey;} .left {height: 100% ...

In-line divs are known for their rebellious nature, refusing to conform to traditional

I'm in need of some assistance with taming my unruly HTML. It seems to be misbehaving lately. The content area on the page I'm currently designing has a two-column layout. Instead of using separate containing divs for each column, I opted for a ...

Using a loop to format the <ol> tag

After creating an HTML script using angular, I was able to successfully display the names in an array as shown below. <div ng-repeat="namep in names"> <li>Name : <span ng-bind="namep.name"></span></li> <li>Age : ...

Organize AngularJS ng-repeat using dictionary information

I'm dealing with a dictionary consisting of key-value pairs, which looks something like this: data = { "key1": 1000, "key2": 2000, "key3": 500 } My goal is to display this data in a table using AngularJS. One way I can achieve this is b ...

Extract time value from html datetimepicker input

Recently, I've been utilizing a datetime_picker that I found on the web to create a value for an html text input. However, I encountered a problem in separating the value into distinct date and time components. When using the date_picker, the TEXT inp ...

The AJAX navigation feature does not function properly on Windows or Safari browsers, whether on a Mac or PC

Currently, I am facing an issue with a menu that is loaded via jQuery but maintained in a separate html file. The purpose of keeping it separate is to update it in one place rather than having to make changes on every page. The menu was functioning properl ...

Efficiently Aligning Elements in CSS both Vertically and Horizontally

I'm struggling to align my form both vertically and horizontally. It's okay if this doesn't work on IE - I will include an IE detection script to prompt users to switch browsers. However, Firefox and Chrome support is essential. Below is m ...

What is preventing FancyBox from functioning properly?

Seeking assistance in implementing FancyBox for an e-commerce website I am developing for a client. Despite trying various tutorials and troubleshooting steps over the course of three days, I have been unable to get it to function properly. Not encounterin ...

Displaying items using the flex property can cause the top resize feature to be unreachable

My issue revolves around the display of input errors, which are causing the top section to become inaccessible. I am looking for a solution that will align the content both vertically and horizontally in the center. The challenge arises when the card conta ...