How come block elements do not automatically adjust to the explicit width of their children when a horizontal scroll is present?

Whenever I resize my browser window horizontally in Chrome or Safari and the window width becomes less than an element's width, a scrollbar appears. When I scroll to the right, the content width matches the viewport width only if it doesn't have a set width. This can cause some content to get cut off.

Here's a simple example:

div {
  border: 1px solid red;
}

.two {
  width: 1000px;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>

(View codepen)

If the .one element is a block and the width defaults to its parent's width, why doesn't it end up being the same width as the larger .two element?

Could it be because the width of the html is based on the viewport and not the entire document?

Answer №1

Your analysis is missing one crucial element - the overflow part. It is accurate to say that one will inherit the width of its parent, but two will not expand the width of its parent; instead, it will overflow it.

If you add a border to the body and html elements, this difference becomes more apparent.

div {
  border: 1px solid red;
}

.two {
  width: 1000px;
}

body {
  border:2px solid;
}
html {
  border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>

Starting from the viewport, all elements are block-level and will have a default width of 100% (html, then body, then one). However, setting the width of two larger creates an overflow without impacting any ancestor elements' widths.

To fully understand how overflow works and when scrollbars are added:

UAs must apply the 'overflow' property set on the root element to the viewport. When the root element is an HTML "HTML" or XHTML "html" element with an HTML "BODY" or XHTML "body" child element, user agents should apply the 'overflow' property from the first child element to the viewport if the value on the root element is 'visible'. The 'visible' value for the viewport should be interpreted as 'auto'. The element propagating the value must have a 'used value for 'overflow' of 'visible'. ref

In our case, we didn't specify an overflow value, so by default, it's visible, resulting in a scrollbar on the viewport rather than the html or body.

Auto

The behavior of the 'auto' value varies between user agents but typically adds a scrolling mechanism for overflowing content boxes.

If you disable overflow within the html or body, no scrollbar will appear:

div {
  border: 1px solid red;
}

.two {
  width: 1000px;
}

body {
  border:2px solid;
  overflow:hidden;
}
html {
  border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>

And for the html:

div {
  border: 1px solid red;
}

.two {
  width: 1000px;
}

body {
  border:2px solid;
}
html {
  border:2px solid green;
  overflow:hidden;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>

Changing your body display property to inline-block will demonstrate that the width increases based on content and is no longer confined to width:100%:

div {
  border: 1px solid red;
}

.two {
  width: 1000px;
}

body {
  border:2px solid;
  display:inline-block;
}
html {
  border:2px solid green;
}
<div class="one">Hello World</div>
<div class="two">Hello World</div>

Answer №2

Block-level elements inherit the width of their parent by default.
Inline elements take up the width of their content only.
(<body> is considered block-level)

<html>
<head>
    <style>
        div {
            border: 1px solid red;
        }
        .two {
            width: 1000px;
        }
        .block {
            border: 2px dotted orange;
        }
        .inline {
            display: inline-block;
            border: 2px dotted blue;
        }
    </style>
</head>
<body>
  <div class='block'>
    <div class='one'>Hello World</div>
    <div class='two'>Hello World</div>
  </div>
  <div class='inline'>
    <div class='one'>Hello World</div>
    <div class='two'>Hello World</div>
  </div>
</body>
</html>

Answer №3

When practicing, all block elements inherit the width of their parent. In this particular scenario, div.one inherits the width of the body. Since the body does not have a specific width set, it then takes the width of the viewport, not the html element.

On the other hand, div.two has a specific width assigned to it without impacting its parent's width (body).

For further information, you can visit the following links: https://www.w3schools.com/html/html_blocks.asp https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth

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

Combining CSS Modules with Ant Design in ReactJs results in compatibility issues

Struggling to implement CSS Modules for styling in my ReactJs project, I followed the ant design documentation found here: . Unfortunately, it's not working as expected when trying to override the component styles of an ant Button. Below is a snippet ...

Problem with CSS layout on Internet Explorer 9

I've encountered some layout difficulties in IE9 and I'm struggling to identify the root of the problem. Even though I'm using Foundation 5, I don't believe that's the issue. The content is within a Foundation grid set at large-12 ...

Creating an endless ticker animation in AngularJS that dynamically adjusts to element dimensions

This is my initial foray into AngularJS, where I am creating a ticker display comprised of boxes. Check out the CodePen here The Code: index.jade: doctype html html(ng-app="ticker") head script(src="../bower_components/angular/angular.js" ...

Activate Popover on Third Click with Bootstrap 4

Is it possible to create a button that triggers a popover after 3 clicks and then automatically dismisses after one click using Bootstrap v4.3.1? Code: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.mi ...

What is the best way to showcase the information from DataProvider in Amcharts visualizations directly beneath each chart?

After creating some graphics using Amcharts, I encountered a challenge in displaying the table of data (dataProvider) right below each graph on my HTML page. Despite searching extensively for a solution, I have been unable to find one. The table of data ...

What is the reason that `font-size` does not match the `height`? For example, if the `<span>` on the left is 2rem, on the right I could fit 2 smaller `<span>`s, each with a size of 1rem

How can I achieve a layout like this? https://i.sstatic.net/rrISu.png Essentially, I have 2 containers in flexbox: The first one with text "33" The second one is a grid container: The first element in the grid is "EUR" The second element in the grid i ...

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

What is the best way to center a specific element within a flex container?

Is there a way to center a specific div within a flex container? Let me explain using some code: Take a look at this code snippet: <html> <head> <style> div.flex_container { display: flex; flex-direct ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

Executing Angular application through Node.js server

I have the following list of files: index.html app.js (angular controllers here) routes.js (I'm attempting to load index.html from here - listening on localhost :3000) index.css node_modules folder routes.js : var express = require(&apo ...

What is the best way to prevent text from being dragged within a contenteditable div?

Currently, I am working on a contenteditable div. This div has a default behavior that allows you to drag pieces of text around. I have tested this behavior on Chrome/Windows only so far. https://i.sstatic.net/IWLsY.gif I am looking for a way to disable ...

How can I resolve the vertical adjustment issue of Bootstrap 5 input group on mobile devices?

My current issue involves using Bootstrap 5.2.3 to create an input group that displays a set of spans with the ".input-group-text" class alongside inputs with the ".form-control" class. While this setup works well on a computer screen, it does not adjust c ...

I am unable to view the map on my webpage. This issue only arises when I apply a CSS style to it

Hey there! I'm having trouble displaying a map on my website. For some reason, the map is not showing up even after updating the Google secret key in my code: <?php session_start(); include '../../WSweb/serv.php'; if(isset($_SESSION[&a ...

Showing data from the POST request in a dialog box

Greetings to all! I am in the process of building a webpage to test my API. The goal is to send a form to my nodejs backend and receive a JSON response back. So far, sending the request is functioning properly and I can track its progress on my VPS conso ...

Looking for a method to emphasize a particular word in a Material-UI Typography component within a Card without causing any alignment changes upon rendering?

Is there a way to bold a single word within a React Material-UI <Typography> element without causing text resizing on load? <Typography><b>First thing:</b> {answers[2]}</Typography> I find myself nesting <Typography> t ...

Ensuring that the second level unordered list is set to a height of 100% of the first unordered list, rather than the

I'm working with this menu http://codepen.io/alexandernst/pen/oxpGYQ (I wanted to include it here but the result viewer on SO is causing some display issues...) and I am trying to ensure that the second and third level ul elements are the same height ...

Customize your Bootstrap design by selecting a background color that doesn't

Why is the dropdown background black when used in a bg-dark navbar but white when used outside of the navbar? I want to use a white dropdown in a dark navbar. Here is my complete code: MyCode Here is my navbar & dropdown: <nav class="na ...

Troubleshooting a Navbar Issue in a Custom Bootstrap Template

I am a beginner in html and bootstrap, but I recently attempted to create my own bootstrap template. Initially, I tried to work with the "starter template" code from getbootstrap.com, but after launching the code and making some changes, the navigation bar ...

Is there a way to display my WhatsApp number, email, and location using icons?

[Apologies for my English not being perfect] I came across this image on and I'm curious about how to add similar WhatsApp, email, and location buttons on my own website. Can anyone assist me with this? Initially, I mistook these elements for images ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...