When the overflow is set to visible, the background color vanishes

Here is the CSS code I have written;

#container {
    width: 1300px;
    background-color:green;
    margin:0 auto;
    overflow:hidden;
}

#menu {
    float:left;
    width:20%;
    background-color: yellow;
}

Even after extensive searching on Google, I have been unable to find an explanation as to why the background color of the container disappears when the container's overflow attribute is set to visible.

Could someone provide some insight into why this happens?


Update:


Thank you for all the feedback and responses! :)

Although I am fine with using overflow:hidden, I am interested in understanding its purpose and how to utilize it effectively.

From what I gather, the overflow property determines what happens when content exceeds an element's boundaries, so I am perplexed as to why setting it to visible would cause the container's background color to vanish or alter the container's height.

Answer №1

Due to the elements having float:left within the container, the container's height was reduced to 0, causing the background to be hidden.

To resolve this issue, there are several solutions available:

One solution is to use clearfix:

<div id="container" class="clearfix">
  <!-- insert floated elements here -->
</div>

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

Another option is to apply overflow:hidden to the container element, creating a new block formatting context that clears the floats. (Refer to this post for more information)

According to the CSS spec:

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

Within a block formatting context, boxes are stacked vertically, starting at the top of a containing block. The vertical spacing between sibling boxes is defined by the 'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.

Within a block formatting context, each box's left outer edge aligns with the left edge of the containing block (in right-to-left layout, right edges align). This holds true even when floats are present (though a box's line boxes may adjust due to the floats), unless the box establishes a new block formatting context (in which case the box itself may narrow due to the floats).

Answer №2

The reason for this issue is the presence of a floating child element within the container. When a container only contains floated elements, its height is reduced to zero.

To fix this problem, there are several solutions you can consider:

  • The Empty Div Technique: Insert a
    <div style="clear: both;"></div>
    as the last child element.
  • The Overflow Solution: Apply overflow: hidden to the container element.
  • The Easy Clearing Approach: Utilize additional CSS and a class on the parent element (clearfix').

    .clearfix:after { content: "."; visibility: hidden; display: block; height: 0; clear: both; }

Answer №3

The reason for this issue is that the #menu does not have a specified height.

Since #container has the height of #menu, the background is not showing.

Make sure to assign a height to the #menu.

#menu {
    float:left;
    width:20%;
    background-color: yellow;
    height:50px;
}

View the demo here.

Answer №4

To ensure that the container div matches the height of the menu div, you can simply set the container's height using jQuery.

$('#container').height($('#menu').height());

Check out the demonstration here: http://jsfiddle.net/er144/1H7aK/

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

Using jQuery to bind the "CTRL+A" key combination to exclusively selecting a specific region

My goal is to modify the CTRL+A shortcut so that instead of selecting all text, it will only select specific content within containers with a class of xyz. Unfortunately, I have not been successful in getting this functionality to work. Even attempting to ...

display rails view using ajax

I have developed a new form that I would like to render using ajax in case it fails validations. In my controller, the code looks like this: def create event = CEvent.new(params[:c_event]) respond_to do |format| if event.save format.html { ...

Personalize the marker design within the Wikitude SDK using JavaScript

Currently, I am developing an augmented reality view in Android using the wikitude-sdk. As part of the project, I am displaying markers on the screen and now I am looking to customize the marker view using the AR.HtmlDrawable method offered by the ...

Elevate your web design by transitioning from Bootstrap 4 to Bootstrap 5

Should I upgrade a large project from Bootstrap 4 to version 5? Will it require extensive changes in each file? After updating my project, many components have stopped working: Dropdowns Accordions and more Is this a common issue experienced by everyo ...

Styling the background of the endAdornment in a material-ui textfield using React

I tried following the instructions from this source: Unfortunately, the example code provided doesn't seem to be functioning properly now. Is there a way to achieve the same result without having that right margin so that it aligns better with the r ...

What is the best way to send HTML tag content to mark.js and delimit them with a space or comma?

I have been utilizing the mark.js library to highlight keywords on a webpage, and it's been working well. However, I now need to insert an extra space or a comma after each tag such as h1, h2, etc. Initially, I thought about using a loop like the one ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

Is the Javascript framework malfunctioning even though the code is identical to the one on jsfiddle

<html> <head> <meta charset="UTF-8"> <title>Interactive Globe Display using iTowns</title> <style> html { height: 100%; } body { margin: 0; overflow: hidden; ...

When the onInput event is triggered, React renders components and console.log() displays different values

When I type in the input field, it triggers the onInputChange() function. This function updates the state of inputValue, and then calls the getValue() function which retrieves the current state of inputValue and logs it to the console. However, the value d ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...

Unable to retrieve API data on local server port 5000. Utilizing a database sourced from a CSV file. Unexpected undefined promise response

I have been struggling for the past few days with a persistent issue. Seeking assistance. Currently working on a project involving a CSV database and creating my own API. It is a small React App Fullstack MERN setup. The specific challenge I am facing is ...

Establishing the maximum width of a Vuetify expansion panel component

https://i.sstatic.net/QqKVv.png I'm currently in the process of developing a webpage using vuetify and nuxt. My main focus right now is adjusting the max-width property of the expansion panel UI component (https://vuetifyjs.com/en/components/expansio ...

What is the best way to ensure Font-Face loads fonts successfully on iOS devices?

In the process of constructing a website with Gatsby.js, Styled-Components, and a custom font named 'Montserrat', I encountered an issue regarding font loading. The font appears as expected on desktop browsers during both build and hot-reloading, ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Using jQuery to trigger several setTimeout() functions in succession

I'm struggling to grasp the concept of jQuery promises. To delve into this topic, I have put together the following code snippet inspired by a discussion on StackOverflow. let functions = [ function () { setTimeout(function () { console.log("func ...

The issue with AngularJS 2-way-binding failing to refresh

Recently, I experimented with angularJS in conjunction with a range-slider-directive that can be found here: https://github.com/supertorio/angular-rangeslider-directive Initially, everything worked well while using the data-model solely within my HTML pa ...

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...

transferring various data from JavaScript page to PHP page

Is it possible to pass multiple values from a service page to a PHP page? I am trying to pass the values 'data', 'albimg' and 'albvideo' to the PHP page, but I keep encountering an error. Please refer to the image below for mo ...