Using `CSS: "height: 100%;"` can cause the normal flow to be disrupted

Consider this straightforward example... something that went unnoticed until now.

HTML:

<body>
    <div class="container">
        <div class="sidebar">
        </div>
    </div>
</body>

CSS:

*, *:before, *:after {
    box-sizing: border-box;
}

html, body, div {
    background: rgba(0, 0, 0, .2);
    margin: 0;
    padding: 20px;
    height: 100%;
    border: 1px solid #000;
}

.container {
    height: 250px;
}
.sidebar {
    width: 20%;
}

setting the height of body to 100% works perfectly in this fiddle.

however, if you expand the size of .container so it goes beyond the initial window size... you will see the div escaping the boundaries of the body container (it even seems to break out of the html container too)?

Reformatted Question

Is there a way to initially set the height of body to 100% of browser window but at the same time allow the parent containers to adjust accordingly if their children extend beyond the window size?

Answer №1

Usually, if you want the html and body elements to match the height of the viewport while still being able to expand with the content, you would set height: 100% on the html element only, and use min-height: 100% instead of height on the body element. For more detailed explanations, refer to my responses in these threads:

  • Height: 100% or min-height: 100% for html and body elements?
  • Applying a background to <html> and/or <body>

Unfortunately, setting min-height on the root html element alone is not feasible as it will disrupt the layout. You require height: 100% because without it, there is no reference parent height for the body and its contents; the height of html is based on the pre-determined viewport height.

If your design involves borders on all these elements, it's recommended to eliminate them unless essential. The background will automatically extend to cover the whole viewport area (explained in the second link).

To resolve this using CSS, just set height: auto on body to counteract the height: 100% from the previous rule, combined with min-height: 100%:

html, body, div {
    background: rgba(0, 0, 0, .2);
    margin: 0;
    padding: 20px;
    height: 100%;
}

body {
    height: auto;
    min-height: 100%;
}

Note that I have removed the borders assuming they are unnecessary.

Another issue arises when the content exceeds the browser height, causing the padding on html to disappear, since html does not expand along with the content due to height: 100% (scroll to the bottom to observe).

You cannot remove height: 100% as it is necessary, but you can adjust the padding on html to margins around body, ensuring the margins remain effective even after body overflows html, resulting in this outcome (again, scroll to the bottom):

html, body, div {
    background: rgba(0, 0, 0, .2);
    margin: 0;
    padding: 20px;
    height: 100%;
}

html {
    padding: 0;
}

body {
    height: auto;
    min-height: 100%;
    margin: 20px;
}

Answer №2

When an element is designated as having a height of 100%, it will typically expand to occupy the full height of its containing parent, excluding any padding applied to the parent element.

Answer №3

After examining your code in Dreamweaver, I discovered that the issue lies with the padding. Everything seems to work fine until it extends beyond the viewport due to changes in height. To fix this problem, I removed the padding. I recommend reconsidering how you arrange your padding or exploring alternatives such as using margin: 5px; on the outer layers instead of padding on the inner layers. Another option is to use a blank fixed-height div and position your inner divs as a percentage, repeating as needed (although this method may be considered unconventional).

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

Adding one class at a time, with each new class being added every second

My goal is to add classes one by one [test0 test1 test2] up to 10, with each class being added after one second. $('.rating-block').AddClass('test0 test1 test2 ... test10' ); I am experimenting with the following code, but I don' ...

Is the Bootstrap carousel sliding to the top after clicking the next and previous buttons?

Here is the carousel I created using Bootstrap: <div id="carouselExample" class="carousel slide d-none d-sm-none d-md-block" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active ...

Unable to modify the focus outline for .custom-control-input within Bootstrap 4

After spending countless hours attempting to change the focus outline color of the custom bootstrap controls, I have hit a roadblock. Changing the background is a breeze with: .custom-control-input:checked~.custom-control-indicator { background-color: re ...

Reading inputs from a Text Area using ko.JS databinding - Issue with capturing new lines

This is the code I have written for a text area: <div> <textarea data-bind="value: environment" rows="10" cols="20" class="form-group"></textarea> </div> https://i.sstatic.net/Pk1NT.png I am looking to show the content typed in ...

Choosing the subsequent div after the current one using Jquery

I am currently in the process of creating a drop-down menu button that, when clicked, reveals the previously hidden div underneath it. The code is functioning properly without the use of $(this).next, but it is displaying all divs with the class .menudrop ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

Please display the "django.db.models.query_utils.DeferredAttribute object at" message in Django

Having trouble retrieving data from a database object to populate and edit a form in HTML. When I try to access the current value from the attribute, I encounter this issue: Form HTML <form enctype="multipart/form-data" method="pos ...

Using CSS to access a different div tag within a div tag

In my CSS, I have a div.xx-wrapper:hover that triggers when hovered on. This action should also trigger two other tags in the CSS: div.slider-nav span.right:hover and div.slider-nav span.left:hover; Essentially, I am trying to create an effect where hover ...

Attempting to relocate the product section beneath the category sections within the sidebar of x-cart 5

Check out this website link: I attempted to rearrange the best seller product section below the category section in the sidebar. I enabled Layout editor mode from the admin end, dragged the best seller products below the category sections, and saved it. I ...

Refreshing PHP Script

I have a PHP file that contains a combination of HTML elements, JavaScript functions, and PHP scripts. I need to rerun a specific part of the PHP script repeatedly. Let's consider the following example: <html> <?php $connection = ...

Creating a stunning image fade-in effect with CSS3

I have been working on a way to make images fade in using CSS3 once they have finished loading. However, I am facing an issue where the image fades in and out for a brief moment twice instead of just being blank and fading in. My attempt at a solution inv ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Eliminate spaces within a string using JavaScript

In my quest for knowledge about trimming strings in JavaScript, I came across this intriguing discussion with a regex-based solution. After learning from the thread, I was under the assumption that trim would eliminate the space between "Hello" and "World ...

What is the best method for storing "game progress" in local storage?

I am currently working on coding a simple Risk game where players can click on countries to change their color from red to green, yellow, purple, and back to white. The game starts with an "all-white" map. I am looking to create different save slots so th ...

Show both sets of data in two tables on one page

Currently, I have two tables named users and vm_tables. I am currently displaying data from the users table in the following manner: $sel_query = "SELECT * FROM users WHERE account_id=".$_SESSION['admin_id']; <td align="left"><?php ech ...

Block Button styles not displaying in IE when set to Full Width

I can't figure out why, but it seems to be functioning properly on every other internet platform except this one. The first picture shows the button in IE, the second contains the code, and the third displays the button in Chrome. https://i.sstatic. ...

Decrease the size of the hyperlink area to only the center portion of the text for a more precise click target

Normal text links are present: <a href="projects.html">Projects</a> Is it feasible to make only the middle part of the letters clickable? Such as excluding the top of 'P' or the bottom of 'j'? a { font-size: 50px; ...

Error encountered - registration form

<?php $mysqli = mysqli_connect('localhost', 'test', 'test123', 'test'); if ($mysqli->connect_errno) { echo "<p>An error occurred while trying to connect: {$mysqli->connect_error}</p>"; ...

Variable Returned by AJAX

I am attempting to send a variable using a select box via POST method, then use AJAX to submit the data and finally leverage that variable on the original page to update SQL queries. Below is the code snippet I currently have: <script type="text/j ...

Not all the divs nested within the main div are having the class applied to them

Here is the HTML code I have: <?php require_once("../RMS/php/component.php") ?> <!DOCTYPE html> <html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-prot ...