What causes the child div to not be centered when using margin and border box?

 <style>
      .parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        margin: 20px;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>

The scenario involves a child div nested within a parent div with padding and margin attributes. One would expect the child div to be centered, similar to the provided image.

https://i.sstatic.net/z5cTx.png

However, when executing the code, the child div appears skewed towards the bottom right corner.

https://i.sstatic.net/kvxc6.png

To address this issue, I attempted using the box-sizing property set to border-box to account for the margin of 20px in the final dimensions but observed no changes. Thus, my queries are: 1) How can I center the child div with applied margin? 2) Why does the border-box attribute not affect the child div as expected?

Answer №1

To make it work, simply delete the margin property. You can find a detailed explanation in this answer: Flex items not respecting margins and box-sizing: border-box.

Don't forget that when using box-sizing: border-box, padding and borders are included in the width and height calculations but margins are always calculated separately.

.parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
      
<body>
    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>

Answer №2

To center the content, removing the margin from the child div is necessary. The margin, being outside of the child div, pushes it to the left.

Here is an example that should work:

 <body>
    <style>
      .parent {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        padding: 20px;
      }
      .child {
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        border: 1px solid blue;
      }
    </style>

    <div id="app">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>

An alternative method is to apply the following CSS on the parent div to center most elements:

        /* display: flex;
        align-items: center;
        justify-content: center; */

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

Add a circular transition effect to Font Awesome icons

Check out my code snippet on JSFIDDLE: https://jsfiddle.net/8f3vLh0a/14/ I am using font awesome icons and I would like to add a circling effect on hover similar to this demo: http://tympanus.net/Tutorials/ResponsiveRetinaReadyMenu/ How can I implement t ...

Stop the text from wrapping to the full width of its parent when it overflows onto the following line

When I shrink the width in responsive design, the text overflows to the next line and the text wrapper expands to fit the parent container. Is there a way to prevent this behavior so that it looks like the red container? I could add padding to the contain ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

Incorporating dynamic HTML content into a Bootstrap 2.3.2 popover

I'm trying to create a dynamic Bootstrap popover with HTML content when hovering over a button. Here's what I have so far: $(".btn.btn-navbar").hover(function() { html = '<ul class="nav"><li><a href="#">hello</li>& ...

CSS: The relative positioned element now functions correctly with the inclusion of overflow-x

Is there a way to ensure that the images in the day_time_block cover the title class? I would also like all contents within the day_time_block to be displayed using overflow-x. However, when I add overflow-x: auto; to the scroll div, the images in the d ...

Ways to stop the floating label from blending with the input field

Attempting to incorporate the Bootstrap Material design theme into my project, I have implemented a basic text input field using the code below: <div class="form-control-wrapper"> <input class="form-control empty" type="text"></input> ...

HTML header with zero margin

Hi there! I am currently learning the basics of HTML and CSS. I have a question regarding creating a header with no margins on the edges. Any advice would be greatly appreciated as I haven't been able to find a clear solution. Below is my code snippet ...

Adding a Video as a Background Button Using HTML and CSS

My attempt to utilize background-image in CSS for the button background was unsuccessful as it only supports images, not videos. Is there a way to set a video as the background of a button? My goal is to create a button with a continuously looped muted v ...

Preparing to load a CSS file in a Polymer element based on certain conditions

I have numerous CSS files with various animations, and I am interested in dynamically loading a CSS file in a Polymer element based on the animation attribute: Is it feasible to bind the {{animation}} value like this: <polymer-element name="yo-dialog" ...

Issue with strange behavior of CSS cursor with images

Is there something blatantly obvious that I'm missing here? My goal is to replace the cursor css property with a png, as shown in this example here I was able to get it working with the 'happy.png' demo, but for some reason it won't wo ...

The ScrollToTop feature in MUI component seems to be malfunctioning when paired with the useScrollTrigger hook

I am in the process of developing a custom ScrollToTop component using MUI's useScrollTrigger hook. More information can be found at this link Feel free to check out the sample code here: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9 ...

Tips for making a fluid DIV expand to fit the entire width of the page

My layout features fixed-width sidebars on the left and right, with a fluid main content area that fills the space in between using float:left. Here's an example: #left-sidebar {width: 200px;} #right-sidebar {width: 300px;} #main-content {margin-left ...

ASP.NET showcases icons in a distinct manner compared to HTML and CSS

I'm encountering an issue while trying to convert HTML/CSS to ASP.NET. In the original HTML, the icons were arranged in a single row of four icons, and for mobile devices, they were displayed in 2x2 rows. When I attempted to copy and paste the HTML wi ...

Create a dynamic HTML design with a resizable left panel and a static right panel. The left panel should not wrap text and display ellipsis if necessary

I am looking to display items in a list with a specific format: |Name | Some other val1| |Very very long no wrap line that...| Some other val2| The right side needs to have a fixed width. The left side should fill al ...

Position DIVs next to each other

After scouring through countless Stack Overflow threads in search of a solution to my issue, I still can't seem to get it right. Everyone suggests using float: left, float:right, overflow: hidden, display: block, etc., but none of them are working for ...

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

My CSS is giving me a bit of trouble with alignment

I have been experimenting with various approaches such as adjusting the size of the divs to tiny dimensions and trying out inline-block or float left and right properties, but I am still unable to achieve the desired result of having my divs positioned s ...

Troubleshooting Boostrap Check Box Styling Problem in MVC 5

My registration form has a problem with the checkbox's alignment. I want the text to appear to the left of the checkbox, in line with the placeholders for the input fields on the page. Currently, the text is either above the checkbox (centered in its ...

What is the best way to adjust the padding on the left and right of the Bootstrap navbar logo and menu items?

I am currently facing an issue with the alignment of the logo and menu on my website. They are currently aligned to the far edges of the screen, and I would like them to remain a set percentage distance away from the extremes, rather than an absolute dista ...

What is the method by which frameworks such as Angular encapsulate CSS within a component?

I have a question out of curiosity, rather than seeking a solution to a specific issue. Can you explain how frameworks such as Angular manage to keep CSS contained within a component and prevent it from spreading across the entire webpage? ...