Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML - Make Child Element Ignore Parent Div's Padding

Tags:

html

css

I've got a header div inside of a container div, and the header has a different background color than the container div.

<div class="container">

    <!-- Header -->
    <header class="site-header">
        <h1>Site Title</h1>
        <h5>Site Description</h5>

        <nav class="site-nav">
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
                <li>Item 4</li>
            </ul>
        </nav>

    </header>

My problem is that the container div has padding on the right and left sides, but I want the header to ignore this padding, so the background color will show full width and not be cut off by the padding.

Here's a jsfiddle of my code: http://jsfiddle.net/6e46fzge/

like image 974
Thomas Spade Avatar asked Apr 01 '15 01:04

Thomas Spade


2 Answers

You can simply use a negative margin of the same amount as the padding,

.site-header{
    margin:0 -30px;
}

http://jsfiddle.net/6e46fzge/1/

like image 183
CBroe Avatar answered Oct 26 '22 05:10

CBroe


If you add negative left/right margin to the .site-header and then add the same value to the left/right padding, you will get the effect that you want.

div.container {
  max-width: 960px;
  margin: 0 auto;
  padding-left: 30px;
  padding-right: 30px;
  background-color: white;
}
.site-header {
  margin: 0 -30px;
  padding: 0 30px;
  border-bottom: 2px dotted #999;
  background-color: yellow;
}
.site-nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
  padding-bottom: 20px;
}
.site-nav ul li {
  padding: 2px;
}
<div class="container">
  <!-- Header -->
  <header class="site-header">
    <h1>Site Title</h1>
    <h5>Site Description</h5>

    <nav class="site-nav">
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
      </ul>
    </nav>
  </header>
</div>
like image 25
Marc Audet Avatar answered Oct 26 '22 05:10

Marc Audet