Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding a child div outside of a container div equally on boths sides with margin: 0 auto

Tags:

html

css

Say I have a div that is containing a child div. The container div is set to margin: 0 auto so when the width is increased, the div expands on both sides. If the div inside this container was also set to margin: 0 auto, is there a way to have this div expand beyond its container div and reach to the right and to the left equally?

The following example shows that when width of the .background is increased beyond the width of container, its size only increases from the right and not from both sides.

the css and html:

.container {
  width: 600px;
  background-color: lightgreen;
  margin: 0 auto;
}
.background {
  width: 300px;
  margin: 0 auto;
  background-color: blue;
}
.content {
  width: 200px;
  background-color: lightblue;
  margin: 0 auto;
}
<div class = "container">
  <div class = "background">
    <div class = "content">
      content
    </div>
  </div>
</div>

http://jsfiddle.net/DpYGm/2/

This is all an attempt to get a banner graphic background image to span the body width of a page but still have the content on the inside of the page to remain the same.

like image 419
Emanegux Avatar asked Jan 14 '23 10:01

Emanegux


2 Answers

Say you want the background div to stick out by 50px on each side. You could do this in your CSS:

.background {
    margin: 0 -50px 0 -50px;
    background-color: #00F;
}

A full example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <style media="all">

      .container {
        width: 500px;
        background-color: lightgreen;
        margin: 0 auto;
        height: 400px; /* for illustration */
      }
      .background {
        margin: 0 -50px;
        background-color: blue;
      }
      .content {
        width: 200px;
        background-color: lightblue;
        margin: 0 auto;
      }

    </style>

  </head>
  <body>

    <div class = "container">
      <div class = "background">
        <div class = "content">
          content
        </div>
      </div>
    </div>

  </body>
</html>
like image 71
ralph.m Avatar answered Jan 21 '23 19:01

ralph.m


For sure:

.container {
    width: 600px;
    background-color: #eee;
    margin: 0 auto;
    padding: 10px 0;
}
.background {
    width: 400px;
    margin: 0 auto;
    background-color: blue;
    padding: 10px 0;
}
.content {
    width: 500px;
    background-color: red;
    margin-left: -50px;
}

http://jsfiddle.net/yBcpu/1/

like image 22
nick Avatar answered Jan 21 '23 21:01

nick