Float-related question: How does setting the width of the second element create confusion with floating?

Here is the HTML code I am working with:

<div class = "block1">hi</div>
<div class = "block2">hi</div>

In one scenario, this is the CSS being used:

.block1 {
    width:100px;
    border:1px solid;
    float: left;
}

.block2 {
    width:100px;
    border:1px solid;
}

This results in this output:

View Jsfiddle Example

Now, in another case, I have the following CSS:

.block1 {
    width:100px;
    border:1px solid;
    float: left;
}

.block2 {
    border:1px solid;
}

Which results in this display:

View Jsfiddle Example

I am curious as to why setting a width causes the second div not to be positioned next to the first div. How can I make the second div sit alongside the first while still maintaining a 100px width? Setting float:left achieves this, but I would like to understand why it is necessary.

Answer №1

When specifying a width for the second div, it is necessary to use float: left; because the div is a block level element. If no width is specified, it will take up the remaining space available. If a width is defined, it will float next to the other floated div if there is enough space. To float it to the right, float: right should be used.

Demo

Edit: Further clarification...

If you do not specify a width

------------------------------------------
               total space                     Legend (/ - empty space)

------------- Example 1 ----------------
div1(floated left) ///////////////////////
                   ^---------------------^
                     This space will be taken 
                by the div which is without width
------------- Example 2 ----------------
div1(floated left)
div2(same size as 1 wont float unless you give float: left;)

 ------------- Example 3 ----------------
 div1(floated left) div2(besides div 1 if widths are different without giving float left)
------------------------------------------

As mentioned, if a width is specified, it should float to the left. It may not work if the same width is given to both div1 and div2. See Reference, changing the width of the second div to 150px makes it work. Demo

However, clearing floats before floating the second div will prevent it from floating next to the first one. Check out this example

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

Two horizontal lines placed side by side on one line

Just getting started with CSS and HTML for a school project here. I currently have 2 vertical lines set up like this. <hr class="topline" width=58% size=3 NOSHADE> <hr class="verticalline" width=0.15% size=1000 NOSHADE> I've ...

Receive the height from the parent element using the box-sizing property set to border-box

Let's talk about a CSS challenge. .parent{box-sizing: border-box; height: 60px; border: 1px solid green;} The child div has its own styling: .child{height:inherit;background: red} Here is the code snippet: ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

The anchor links fail to navigate to specific page sections when refreshing the browser or navigating back and forth

I've created a webpage using HTML that contains links within the page. <div> <a href="#first">first</a> <a href="#second">second</a> <div id="first">First div</div> <div id="second">Second div</div&g ...

Switching downlink to top link when scrolling downwards

I have a downward scrolling link on my homepage that moves the page down when clicked by the user. However, I am struggling to make it change to a "back to top" link as soon as the user scrolls 10 pixels from the top. Additionally, I am having trouble with ...

The footer of the website remains separate from the overlay of the modal Popup Form

I recently implemented a modal popup form on my website that covers the entire viewport with its background. However, I am facing an issue where the footer of the website is still displayed on top of the modal background, even though everything else seems ...

Adjust the width of a child element to be within the bounds of its parent's width and maximum width

I am looking to create a CSS menu with specific constraints: The height and width of the parent <div> are variable The number of <li> elements is unknown The <ul> must be at least as wide as the <div> Each row of <li> should ...

Introducing a novel class designed to leverage the attributes of another class

Is there a way to use the @extend feature in CSS to inherit properties from one class to another? Imagine having two CSS files loading on a page in this order: <link rel="stylesheet" href="/css/one.css" media="screen"> <link rel="stylesheet" href ...

What types of HTML elements are compatible with the onbeforeunload function?

Are there any HTML tags that support the onbeforeunload event similar to the window.onbeforeunload event? The iframe tag has an onload event but not an onbeforeunload event. Thank you and best regards. ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Transform the text with a stylish touch within a 'textarea' element

I am currently working on a form with the following design: At the moment, I am at this particular stage and focusing on some minor details: One issue I have encountered is that the "Your text..." appears stuck to the top left corner of the textarea. I a ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

Show a live feed of rows from a SQL database table

I've been struggling with this issue for more than a week now. I have an offline SQL database/website set up where the browser screen is divided into two sections - the full table displayed at the bottom with limited details, and a styled version of i ...

What are the steps to create a downpour in every location on Earth

Is there a way to create a continuous raining effect for my weather app using CSS only? I have achieved a satisfactory look, but the rain effects seem to only cover random chunks of the screen rather than the entire screen. How can I make it cover the enti ...

A distinctive web page featuring an engaging image backdrop: captivating content effortlessly scrolling beneath

On my website, I have implemented a background image with a fixed transparent header. When scrolling down, I want the main content to be hidden beneath the header. To achieve this effect, I used the -webkit-mask-image property. However, this approach affec ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

Transparent PNG slider images with fixed background

I am encountering a strange issue with one of our projects Here on We have an images-menu created using the Kwicks script. The problem arises when we use .png format images that are partially transparent. When these images slide over each other, the bott ...

The hover effect is not functioning upon loading

Demo: http://jsbin.com/afixay/3/edit 1) Hover over the red box. 2) Without moving the cursor, press ctrl+r to reload the page. 3) No alert will appear. However, an alert will pop up once you move the cursor away and hover back over the box. The issue h ...

Ways to ensure the background color stretches the entire length of the page

I've been attempting to create a background image or color that extends across the entire main content area, but haven't had any success so far. For reference, please visit My attempts have involved adding a class called fill to the container-f ...

Retrieving HTML DOM elements using the file_get_contents function

When using file_get_contents to fetch HTML content from a website, I encountered a table within the HTML structure that I need to extract data from. Here is an example of how I retrieve the HTML data from a URL: $url = 'http://example.com'; $con ...