'How to make div 100% width when parent tag has padding?

I have an HTML page where the body tag has CSS padding-left and padding-right applied. I'd like the page footer div to be 100% width of the page though, without the body padding applied. Is there a good/easy way of doing this ?



Solution 1:[1]

If you give the footer a left and right margin that is a negative amount, of equal size to the padding of the body, then it will counter the body's padding.

body {
    padding-left:10px;
    padding-right:10px;
}
.footer {
    margin-left:-10px;
    margin-right:-10px;
}

Solution 2:[2]

Another alternative way can be this : using calc

<div class="parent"> <!--/ Parent div with padding left right -->
    <div class="child">i'm Child div</div>
</body>

CSS

.parent{
   padding:0 20px;
}
.child{
    width:-moz-calc(100% - 40px); <!--/ similar with other browser prefixes -->
    width:calc(100% - 40px);
}

Solution 3:[3]

There is another way of solving this using calc on the parent element. That way, both the padding and the calc are in the same CSS class, and if the padding has to be modified you will see more easily that the calc formula has to be modified too than if it lies in the child element CSS class.

html,
body {
  width: 100%;
  height: 100%;
  padding: 9;
  margin: 0;
}

.parent {
  width: calc(100% - 40px);    /* 40px: 2 * 20px padding */
  height: calc(100% - 50px);   /* 50px: 2 * 25px padding */
  padding: 25px 20px;
  box-sizing: content-box;
  background-color: tomato;
}

.child {
  width: 100%;
  height: 100%;
  background-color: #fbf7e5;
}
<div class="parent">
  <div class="child"></div>
</div>

Solution 4:[4]

After some playing around, 'width: inherit;' solved it for me:

#parent-container {
  width: 400px; 
  padding: 0 15px;
}

#inner-div {
  width: inherit;
  margin: 0 -15px;
}

Solution 5:[5]

Not sure if that is for your case specifically, but i had a form (trying to code for responsive), width:100% and needed padding in inputfields so the solution was

form {
   margin: 0px 3%;
   width: 94%;
}
input:valid, textarea:valid {
   width: inherit;
   padding: 15px;
}

Inherit on fields just did the trick. (Only tested in chrome)

Update: noticed that this breaks graphical layout with some pixels, also here is a good illustration: http://theturninggate.net/2012/01/better-responsive-forms/

Solution 6:[6]

When a flexbox layout used and a generic solution needed (say you do not want to be aware of the parent's padding sizes) the following shall be used (pay attention to the box-sizing property on parent:

.parent {
    display: flex;
    flex-direction: column;
    padding: 48px;
    box-sizing: border-box;
}

.child {
    width: 100%;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leon Bambrick
Solution 2 Suman KC
Solution 3
Solution 4 Tom Durkin
Solution 5
Solution 6 GullerYA