Ensure that the child element completely fills the parent element while maintaining a padding around the edges

How can I create a child div that fills 100% of the parent's width and height, including padding? I've tried using box-sizing = border-box, but it isn't working. I also attempted adding the box-sizing property to all elements with *, but that didn't change anything either. Here is my code snippet:

html {
  font-size: 16px;
}

.parent {
  font-size: 1rem;
  width: 10em;
  height: 10em;
  padding: 5em;
  background-color: #f0f0f0;
}

.child {
  background-color: #ccc;
  width: 100%;
  height: 100%;
  
/* 
--= 100% should include padding =--
box-sizing: border-box; <-- this didn't change anything...
*/
}
<div class="parent">
  <div class="child"></div>
</div>

Answer №1

If a child element is positioned absolutely in relation to its parent, it will be placed outside the parent's padding. To achieve this, use position:absolute as follows:

.parent {
  position: relative;
  padding: 2em;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Visual Example:

html {
  font-size: 12px;
}
body {
  margin: 1em;
}

.parent {
  position: relative;
  font-size: 1.2em;
  width: 10em;
  padding: 2em;
  margin:1em 0 0;
  background-color: blue;
  border: 5px solid red;
}

.child {
  position: relative;
  background-color: lightgreen;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

p {
  margin: 0;
}
.red {
  color: red;
}
.blue {
  color: blue;
}
.green {
  color: green;
}
<p>Parent Border: <span class="red">Red</span></p>
<p>Parent Background: <span class="blue">Blue</span> (not visible)</p>
<p>Child Background: <span class="green">Green</span></p>

<div class="parent">
  <div class="child background"></div>
  <div class="child">This text to indicate parent's padding</div>
</div>

Implementation with your code:

html {
  font-size: 16px;
}

.parent {
  position: relative; /* ADDED */
  font-size: 1rem;
  width: 10em;
  height: 10em;
  padding: 5em;
  background-color: #f0f0f0;
}

.child {
  position: absolute; /* ADDED */
  left: 0; /* ADDED */
  top :0; /* ADDED */
  background-color: #ccc;
  width: 100%;
  height: 100%;
}
<div class="parent">
  <div class="child"></div>
</div>


An Overview:

In the absolute positioning scenario, a box is exactly offset with regard to its container block.

Absolute positioning @ w3

When the position property is set to static or relative, the container block is established by the edge of the content box of the closest ancestral element that functions as a block container...

When the position property is set to absolute, the container block is defined by the edge of the padding box of the nearest ancestral element that has a position value other than static (fixed, absolute, relative, or sticky).

Identifying the containing block @ moz

Emphasis and bold added for emphasis.

For more information: box model

Answer №2

To achieve this without altering the parent element, you can override the parent element's padding. Start by setting the width and height to calc(100% + 10em). Additionally, adjust the left and top padding values to position the element correctly. Ensure that the child element has position: relative, and set left and top to -5em.

html {
  font-size: 16px;
}

.parent {
  font-size: 1rem;
  width: 10em;
  height: 10em;
  padding: 5em;
  background-color: #f0f0f0;
}

.child {
  background-color: #ccc;
  width: calc(100% + 10em);
  height: calc(100% + 10em);
  position: relative;
  left: -5em;
  top: -5em;
}
<div class="parent">
  <div class="child"></div>
</div>

Answer №3

To reposition the child element, your child should set its margin to the negative value of the parent's padding. This will return the component to its original position before the padding was added to the parent. Remember, this adjustment can be made in any direction.

Due to the additional padding applied to the parent, the parent's dimensions have increased. Horizontally, this increase is from the sum of left and right paddings. Vertically, it results from the combination of top and bottom paddings.

html {
  font-size: 16px;
}

.parent {
  font-size: 1rem;
  width: 10em;
  height: 10em;
  padding: 5em;
  background-color: #f0f0f0;
}

.child {
  background-color: #ccc;
  width: calc(100% + 5em + 5em); /* parent's width + left-padding + right-padding */
  height: calc(100% + 5em + 5em); /* parent's height + top-padding + bottom-padding */
  margin: calc(5em * -1); /* The negative of parent's padding */
}
<div class="parent">
  <div class="child"></div>
</div>

For your specific scenario, a more straightforward approach for the child component would be:

.child {
  background-color: #ccc;
  width: 200%;
  height: 200%;
  margin: -5em;
}

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

What are some strategies for ensuring that Plotly JS can adapt its height and width to fit the entire div dynamically, without relying on fixed pixel dimensions?

Is there a way to ensure that Plotly automatically adjusts to the size of the container #myDiv without any noticeable delay when the top button is clicked? This code snippet demonstrates a high delay: var z = [], steps = [], i; for (i = 0; i < 500; i+ ...

When using Angular 5's ngModel, the user interface displays the updated value dynamically without requiring the

When filling out my form, I encounter an issue with a select element and a bind variable. If I make a change to the value and save it, everything works as expected. However, if I make a change in a modal window but then close the modal without saving the v ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

Button with tooltip for easy access to trigger a modal dialog

My task involves creating a button with a tooltip that displays simple statistical information to the user, such as a student's grades (e.g., "Homework: 100%, Exams: 85%"). Upon clicking the button, a modal should appear with more detailed information ...

Difficulty in aligning Grid elements in Material UI version 5

Strange enough, the MUI5 Grid is displaying unexpected spacing behavior. Instead of providing proper spacing between items and containers, it seems to be causing them to overlap. To see a live example, visit: https://codesandbox.io/s/green-worker-z44vds? ...

Is there a way for me to discover the identity of the victor?

There are 4 divs that move at different, random speeds each time. I am trying to determine which one is the fastest or reaches the goal first. Additionally, there is a betting box where you can choose a horse to bet on. I need to compare the winner with my ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

Trouble with visibility of Bootstrap navbar collapse button

While creating an application using bootstrap, I encountered a problem with the navigation bar. The issue is that when I resize the page, the links disappear and the toggle button fails to show up. Below is my current navigation bar code: <link rel= ...

Comparison of HTML's equivalent to LaTeX's label and ef functionality

I have a Frequently Asked Questions page coded in HTML (example) where the questions often refer to one another. This results in the numbering changing whenever we add, delete, or rearrange the questions. LaTeX provides an elegant solution to this problem ...

Tips for preserving a string in angularJS or Java (and implementing it in an iframe)

My plan involves utilizing a Java web service to fetch the HTML content from a specific URL using Jsoup, and then returning it as a string to the requesting party, which could be an Angular or JS script. I am keen on preserving this content somewhere and l ...

Utilizing jQuery Mobile - Dividing content across multiple HTML files

In the process of developing a web application utilizing jQuery and jQuery mobile, I am aiming to display various pages. Given that the corresponding html-markup may become lengthy, I am interested in dividing the html into separate files. For instance: & ...

Getting error messages for form validation in CodeIgniter when using Fileupload via Ajax can be tricky. Here are

Hello, I am currently working on retrieving form errors for an input type file in CodeIgniter. I have created a Javascript code that utilizes Ajax to submit the details as shown below: var name = $("#name").val(); var des = $("#des").val(); var img=$("#fi ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery ca ...

Looking for browser prefixes for the `text-align` property? We've got you covered! Use `-webkit-right` for Google Chrome and Safari, `-moz-right` for Firefox, and `-o-right` for Opera. But what about

When it comes to browser prefixes or hacks, we often think of: (for Google and Safari) text-align: -webkit-right; (for Firefox) text-align: -moz-right; (for Opera) text-align: -o-right; But what about Internet Explorer? I'v ...

HTML's Nesting Buttons for Enhanced Interactivity

Can anyone help me figure out why the inner buttons in my HTML code are displaying outside of the parent button? I am attempting to showcase buttons inside a large button on my webpage. Your feedback on what I might be doing wrong here would be greatly a ...

Issue with switching button and content positioned absolutely

Within this container, I have some content followed by a slide toggle button and then more content. The toggle button utilizes the jQuery function slideToggle. All elements within are positioned absolutely. [Introduction Content] Toggle Button [Hidden C ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Having trouble selecting a button using xpath in Scrapy Python?

I am currently attempting to scrape quotes from a website called using my spider code that looks something like this: class quote(scrapy.Spider): name = 'quotes' # defining Name start_urls = [''] # Targeted urls def parse(s ...