Deploying a child div outside the div container is the same on both sides with a field: 0 auto

Let's say I have a div containing a child div. The div container is set to margin: 0 auto, so when the width increases, the div expands on both sides. If the div inside this container was also set to margin: 0 auto, is there a way for this div to expand beyond its container div and go right and left the same way?

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

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/

All this is an attempt to get a graphic background image of the banner to cover the width of the body of the page, but the content on the inside of the page will remain the same.

+4
source share
3 answers

Suppose you want the background div to stick out 50 pixels on each side. You can do this in your CSS:

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

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> 
+3
source

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/

+3
source

There is a more semantic way to achieve this, depending on your reasoning:

 .container { background: green url(../path-to-image.jpg) no-repeat top center; margin: 0 auto; min-height:300px; } .content { width: 500px; background-color: red; margin: 0 auto; min-height: 300px; } 

Attach the background image to the .container with the top center of the position.

http://jsfiddle.net/DpYGm/5/

0
source

Source: https://habr.com/ru/post/1479554/


All Articles