Centering a div that is wider than its parent without setting a negative left margin

I have a div inside a div.

The inside of the div is larger than its parent, so the usual procedure

margin-left: auto; margin-right: auto; 

creates an inner div where the left edge of the child is aligned with the left edge of the parent.

When people answer this question, they use to search for the negative left edge. Is there a cleaner solution?

+7
css
source share
4 answers

How about using position: absolute; with left:0;right:0; and margin: auto;

In addition, you need to place position: relative; in a parent element that is wider than the outer element. (In the violin below with respect to the body by default)

Fiddle

 <div class="outer"> <div class="inner"></div> </div> 

CSS

 .outer { width: 400px; height: 400px; background: beige; margin: 0 auto; } .inner { width: 600px; height: 200px; background: pink; position: absolute; left:0;right:0; margin: auto; } 
+5
source share

You can use flexbox:

 .outer { display: flex; /* Magic begins */ justify-content: center; /* Center contents */ width: 400px; height: 400px; background: beige; margin: 0 auto; } .inner { flex-shrink: 0; /* Don't shrink it even if it too wide */ width: 600px; height: 200px; background: pink; } 
 <div class="outer"> <div class="inner"></div> </div> 
+6
source share

If the inside is an image, I prefer this
background: url("../img/pic.jpg") no-repeat center center fixed; -moz-background-size: cover; -webkit-background-size: cover; -o-background-size: cover; background-size: cover;

0
source share

Use absolute positioning with dynamically calculated values. This works for any width of two divs:

 <!DOCTYPE HTML> <html> <title>Center DIVs</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> $(document).ready(function(){ function centerDIV(){ var parentWidth = $('.parent').width(); var childWidth = $('.child').width(); var x_pos = (parentWidth/2) - (childWidth/2); $('.child').css('left', x_pos); } centerDIV(); }); </script> <style> .parent { width:200px; height:200px; margin:0 auto; background:red; position:relative; } .child { width:300px; height:100px; background:green; position:absolute; top:10px; } </style> </head> <body> <div class="parent"> <div class="child">Content for class "child" Goes Here</div> </div> </body> </html> 
-3
source share

All Articles