Arranging block-level elements in a horizontal format

In the book "CSS The definitive Guide", it is mentioned that "The values of these seven properties must add up to the width of the element’s containing block, which is usually the value of width for a block element’s parent". However, in the case provided below, the child element appears wider than its parent.

//html

<div class="wrapper">
    <div class="content-main">
        <div class="main">This is main</div>
    </div>
</div>

// style

        .wrapper {
            width: 500px;
            padding: 30px 0;
            border: 1px solid #0066cc;
        }

        .content-main {
            padding: 0 20px;
            border: 2px solid #00CC33;
        }

        .main {
            width: 500px;
            border: 1px solid #f00;
        }

There are two questions that arise:

  1. What exactly does the author mean by the statement "the seven properties must add up to the width of the element’s containing block"?

  2. Why does the child element protrude from its parent in the given example?

  3. In the revised version, where the seven properties do add up correctly, why does this equation not apply to the initial example?

EDIT VERSION

p.wide has a width of 438px, as calculated by the author with the following equation

10px(left margin) + 1(left border) + 0 + 438px + 0 + 1(right border) – 50px(right margin) = 400px(parent width)

// HTML

<div>
  <p class="wide">A paragraph</p>
  <p>Another paragraph</p>
</div>

// CSS

div {width: 400px; border: 3px solid black;}
p.wide {
   margin-left: 10px; width: auto; margin-right: -50px;
   border: 1px solid #f00;
}

Answer №1

What is the significance of the statement "seven properties must add up to the width of the element’s containing block"?

The author is explaining the CSS Box Model. In this context, when using div elements, which are inherently block level, they occupy the entire horizontal space by default unlike span, i, or b tags that are inline elements.

When adding padding or border, they are included outside the element, not within it. For instance, if you have an element sized 100x100 and add a padding like

element {
   width: 100px;
   height: 100px;
   padding: 10px;
}

In this case, your element will be 120x120 because it adds a padding of 10px on all four sides of the element.


Explanation of padding syntax

There are two different padding syntaxes as follows...

padding: 30px 0; in .wrapper and padding: 0 20px; in .content-main, these are not equivalent.

Both of the above syntaxes are shorthand versions of padding. The complete version looks like...

padding: 5px 10px 15px 20px; /*This is just a demo */

In the above example, you proceed clockwise with the values - 5px for top, then right, next bottom, and finally left as 20px.

When only two parameters are defined, it means...

padding: 0 20px;
      --^---^---
top bottom/left right

Hence, top and bottom are set to 0 while right and left are set to 20px respectively...


Understanding the CSS

Note: The height of none of the elements is explicitly set, so the screen views provided ahead are computed. Disregard the height for now in those screenshots.

.wrapper {
    width: 500px;
    padding: 30px 0;
    border: 1px solid #0066cc;
}

In this case, your element is 502px wide. Why? Because the border adds 1px on all four sides of the element, while the padding is applied only to top and bottom. Using tools like Firebug would visually demonstrate what's happening behind the scenes.


Looking at the second snippet with the following syntax:

.content-main {
    padding: 0 20px;
    border: 2px solid #00CC33;
}

Here, a 2px border is added to your element, but the padding now affects left and right instead of top and bottom. The calculation changes accordingly.


Finally, examining the last snippet:

.main {
    width: 500px;
    border: 1px solid #f00;
}

Only a border is applied here, causing the element to overflow due to the defined width of 500px. The padding set for the parent element nudges the child element by 20px from the left side. A Firebug screenshot illustrates this nudge.

Reason for the element sticking out of the parent in my example.

This occurs because a width of 500px is specified for the .main div.

Demo (Effects of removing the width)


The default box model is referred to as content-box

You can modify this by utilizing the new CSS3 property called box-sizing set to border-box. This alters the box-model to include the padding and border inside the element rather than outside.

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

Creating a dynamic webpage using Javascript that responds to user clicks on page links

I am interested in the process of inserting JavaScript objects from a JSON file in order to dynamically create a unique page based on a user's clicked link. This concept is similar to having a wildcard page in popular frameworks like Laravel or Django ...

The method of document.getElementsByName does not provide any results

I am a beginner in using python flask and understanding the MVC concept. My goal is to display the selected option in a dropdown list. Below is my list defined in a .py function. @app.route('/', methods=['GET']) def dropdown2(): ...

Creating an array using Vue.js

When I initialize a Vue data array like this [0: Object, 2: Object];, the console log in Vue shows the array as [0: Object, 1: undefined 2: Object];. This causes issues when iterating through with 'v-for="cell in row.cells"' as it results in tryi ...

The clickable area for the radio button cursor is too large

As I embark on my journey with HTML and CSS, I have encountered two issues while creating a form: The spacing between the question and answers is too wide. The second picture depicts how I would like it to appear. The cursor:pointer seems to be extending ...

What is the best way to use AngularJS to extract values from the first dropdown menu that are linked to the values selected in the second

How can I link values in two dropdowns using AngularJS? Hello everyone, I have set up two dropdown fields in MyPlunker and within the ng-option tag, I have applied a filter like filter:{roles: 'kp'} to only display users with the role of kp. T ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Experiencing issues with a malfunctioning Chrome extension? The CaptureVisibleTab feature seems to be failing when using

Whenever I try to use the captureVisibleTab function on a page where I have a div with preserve3d in CSS3, all I see is a blank page. How can I solve this issue? Here is my simple code for capturing the browser screen: chrome.browserAction.onClicked.addL ...

conflicting character encoding systems

Request normally comes in this format: Parameters: {"utf8"=>"✓", "status_id"=>"12686"} However, from one particular client, the request looks like this: Parameters: {"utf8"=>"\xE2??", "status_id"=>"12686"} As a result, I am encounter ...

"Utilize the inline display property to keep elements hidden

I have created a template named 'aTemplate' using the following code: $.template('aTemplate', '<div id="someid" class="abc">' + .... '</div>' ); My goal is to make this div inline with other ele ...

Capturing keydown events exclusively in the topmost layer of the HTML document

Currently, I am developing a web application that includes an underlying HTML file with some JavaScript functionality that I cannot modify. In my code, I create a layer on top of this page using CSS with z-index: 1000;. However, I am facing an issue where ...

Creating a loading mask for a section of a webpage using angularjs

How can I implement a loading mask/image for a $http request that loads data for a <select> tag on my webpage? I want the loading mask/image to only cover the specific section of the page where the data is being loaded. Here's the HTML code: & ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...

Website Task Organizer for Effective Online Management

I need assistance with a task management system I am developing for a class project. The system is not functioning correctly as information is getting lost before reaching the server and some PHP code snippets are visible on the website. Can someone please ...

Tips for appending the id of an active element to a URL

My goal was to include the id value of the active element in a URL and then redirect to that URL with a button click. HTML <div class="icon" tabindex="0" id="company"> <img src="company.png"> </div> <button type="submit" onclick= ...

Ways to eliminate project title from the URL

After removing the hash tag from the URL with $locationProvider.html5Mode(true), I attempted to address the refresh issue by adding the following code to my .htaccess file: Options +FollowSymlinks RewriteEngine On RewriteBase /test/ RewriteCond %{REQUEST_ ...

Achieving equal height divs using Bootstrap

I have a row of 8 divs arranged horizontally, and I am looking to make them all the same height. Right now, their heights vary based on the content inside each one. Can someone offer some assistance? I've attempted multiple solutions without success s ...

Discover the steps to trigger a Bootstrap popup modal when clicking on an anchor link using Angular

I have an Angular application and I would like to display a Bootstrap popup modal when the user clicks on a link in the footer. Here is the Bootstrap modal code: <button type="button" class="btn btn-primary" data-toggle="modal&q ...

Inheriting the viewBox attribute with SvgIcon

I have a collection of unique custom SVGs, each with its own distinct viewBox. First Custom SVG <svg viewBox="-4 -4 24 24"><path something/></svg> Second Custom SVG <svg viewBox="-5 -7 24 24"><path something ...

Internet Explorer 11 has a problem with excessive shrinking of flex items

I have a flexbox setup with a left and right section, each of equal width. The left side displays an image and the right side contains text. While this layout works fine in Google Chrome, it does not wrap properly in Internet Explorer 11 when the width is ...

Getting the result from HTML5 FileReader: How does it work?

Dealing with the asynchronous nature of JS FileReader can be challenging. I need to retrieve the result after reading a file and work with that data, but I don't know when the result will be ready. How can I handle this situation effectively? $(docum ...