The div refuses to align beside the previous div that is not floating

Recently, while experimenting with CSS and floating elements, I encountered an unexpected behavior that caught me off guard. I found myself questioning why this had never come up before.

If you have a div (let's call him Bob) and try to float him next to another div (let's name him Jimmy), it only works if

  1. Jimmy is also floated
  2. Jimmy comes after Bob

For example:

<div class="container">
    <div id="one">Main Content 1</div>
    <div id="two">Sidebar 1</div>
</div>

with

.container { 
    overflow:hidden; /* this essentially clears the floats. You could remove it and add a clearfloat div instead */
    margin-bottom:10px;
}
#one {
    background-color:red;
    margin-right:50px;
}
#two {
    width:50px;
    float:right;
    background-color:blue;
}

the layout looks normal, but if we switch #one and #two, keeping the same CSS:

<div class="container">
    <div id="two">Sidebar 2</div>
    <div id="one">Main Content 2</div>
</div>

we see a different outcome.

The reason behind this behavior likely relates to the box model and how floats are defined, but what exactly?

Feel free to experiment with it here

Answer №1

To better understand, try removing the margin-right:50px;.

A block element naturally spans the entire width of its parent container. Even if you specify a width, it's just for visual purposes and does not affect the box model.

When you float an element, it will position itself at the first available floatable space within its parent element. In the first example, this is below the preceding block element. In the second example, it will be positioned at the top.

If you wish to achieve the result seen in example 2 using example 1, simply add float:left; to #one.

Answer №2

This behavior is to be anticipated.

It's important to note that floated elements do not adhere to the normal flow. More details can be found in the following specification:

A floated box is moved to the left or right until it touches the edge of its containing block or another float. If there is a line box, the top outer edge of the floated box aligns with the current line box's top.

In your second example, div#two is removed from the document flow and shifted to the right until it meets the edge of its sibling, div#one. With a margin of 50px;, there is ample space for div#two to fit.

As for your first example, div#one has already cleared that line as a block level element, causing div#two to float right and align with the top of the current line.

For further information, refer to the W3C CSS2.1 Specification on Floats

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

Dealing with Errors in a POST Request using Angular

I have been following the instructions provided in the official Angular documentation found at https://angular.io/guide/http. I encountered an issue with the handleError function within the post request, as it requires 2 arguments and is displaying an err ...

Changing the appearance of a label upon checking an input is unsuccessful

Encountering an issue with modifying labels associated with a specific input. While changing a subsequent div upon checking the appropriate input (checkbox) works seamlessly, attempting the same approach for labels yields failure results. Even wrapping a l ...

Making the black background stretch to the full height and allowing for scrolling when necessary

Check out this webpage where the text in the box extends beyond the page when scrolling, revealing the full content while the black background expands correctly. Visit this page to see that the text in the box is small, but I want the black background t ...

What strategies can I use to dynamically update the .active class in jquery so it doesn't only target the initial one?

Utilizing bootstrap for tab-fade functionality has been successful so far. However, I am facing an issue when trying to select multiple active classes instead of just one. My current JQuery code only changes the text in the first element with the "active" ...

Steps to create a floating navbar using tailwindcss

Here is the code snippet for the site header component: export function SiteHeader() { return ( <header className="fixed top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60&qu ...

How can I customize the appearance of a disabled radio button within spans?

While attempting to make my radio button square using CSS by incorporating spans and before and after elements, I encountered a new client request. The client now wants the radio buttons to be disabled with a unique style when in this state. Unfortunately, ...

What is the best way to incorporate CSS conditions within a function?

After creating a filter function in React to organize images by category, I encountered an issue where the filtered images weren't centered as I wanted them to be. I am now looking for a way to integrate centering into the filtering process so that wh ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Hover over a row in one table to modify the appearance of another row in a different table

Is there a way to change the appearance of rows in one table when hovering over rows in another table that are related? You can find a JSFiddle link illustrating what I am trying to achieve. Here is an example of the code: table#table1 #el1:hover + ta ...

The issue of exceeding margins

I am facing an issue with some CSS. Below is my HTML code: <body> <div id="cn"> <div id="hd"> <ul> <some li's> </ul> </div><!-- /#hd --> <div id="bd"> ...

What is the best way to emphasize the color in a <ul> when one of its children is clicked

I have a variety of links listed on the left side of my website. Here is an example: home categories aboutus contactus When I click on "home" in the list, the page submits and then loads. After loading, I want the "home" link to be highlighted, similar ...

The route function is not being executed

I'm currently developing a straightforward restaurant web application that utilizes a mongo-db database to manage the menu items. The problem lies with my client js file, which is supposed to utilize a routing function to access the database and retri ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Issue with Slick Slider: Next Arrow not visible

I'm attempting to display the next and previous arrows alongside the product slider, similar to the Slick Slider example. However, I'm facing an issue where the expected fonts are not loading properly. Below is my code: HTML <div class="s ...

Is your footer Jumbotron failing to stay at the bottom of the webpage?

I need help with creating a fixed footer using a jumbotron that contains a text area and a button. Here is the code snippet I currently have at the end of the <body>: <div class="jumbotron jumbotron-fluid position-fixed fixed-bottom"> < ...

Implementing Dynamic Parent Node Manipulation with Button Clicks in JavaScript

I am currently working on dynamically creating an input field using the append child method along with add and delete buttons to form a tree-like structure. The goal is to be able to create child nodes with add and delete buttons upon clicking the add butt ...

Ways to incorporate a notification feature with an icon or image

I'm looking to create a visually dynamic icon/image similar to mobile device notifications, but primarily for desktop use. This image will be positioned before some text. For instance: https://i.sstatic.net/MHocy.pngSome Text This design features tw ...

How can I display multiple images in a single row using PHP echo?

I am struggling with my PHP code that displays images from a database. The issue I'm facing is that the images are all appearing in a single column, but I want them to be displayed in one row so that users can scroll horizontally to view them. How can ...

Stretchable navigation cell

I am working on a navigation bar called "nav" that consists of a "ul" and "li". I have specified the display property for the "ul" as table and for the "li" as table-cell. Setting the "ul" to take up the full width of the wrapper ensures proper alignment. ...