Large div centered in a smaller div

I have a div ( #containment ) inside another div ( #edit ). The outer div is smaller. The inner size of the div will be resized by some jQuery code.

I want to make the inner div always centered inside the outer div.

 <div id="edit"><div id="containment"></div></div> #edit { width:200px; height:200px; overflow:visible; margin-top:100px; background:gray; } #containment { width:500px; height:500px; opacity:0.5; background:red } 

fiddle

How can i do this?

+6
source share
3 answers

Updated script

 #containment{ width:500px; height:500px; opacity:0.5; background:red; position : absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } 

Using transform , you are not dependent on the width and height of the parent container. For browser support see caniuse .

The left and top properties set the top left edge of the element to the center of the parent. Using translate , it shifts the X- and Y-position back 50 percent of its own size.

For more information on transform , see developer.mozilla.org - transform

+18
source

The child <div> must have the following CSS properties

 position: relative; width: 500px; height: 500px; left: 50%; margin-left: -250px; /* -(width/2) */ top: 50%; margin-top: -250px; /* -(height/2) */ 

So, if you change the child div via jQuery, then you must recalculate the fields ...

Jsfiddle

http://jsfiddle.net/gvee/fzAge/5/

Initialized CSS

 #edit { overflow: hidden; } #containment { background-image: url(http://placekitten.com/500/500); position: relative; left: 50%; top: 50%; margin-left: -250px; margin-top: -250px; } 

JQuery

 $('#edit').click(function() { var newWidth = 100 + Math.floor(Math.random() * 500); var newHeight = 100 + Math.floor(Math.random() * 500); // Resize the child div $('#containment').width(newWidth).height(newHeight); // Let assign a new background too, eh! $('#containment').css({'background-image': 'url(http://placekitten.com/' + newWidth + '/' + newHeight + ')'}); // Now re-calculate the margins... var newLeftMargin = (newWidth / -2); var newTopMargin = (newHeight / -2); $('#containment').css({'margin-left': newLeftMargin, 'margin-top': newTopMargin}); }); 
+3
source

Yes. Can you do this.

 #edit{ width:200px; height:200px; overflow:visible; margin:200px 0 0 200px; background:gray; position : relative; } #containment{ width:500px; height:500px; opacity:0.5; background:red; position : absolute; top : -150px; left : -150px; } 

Demo: http://jsfiddle.net/fzAge/2/

+2
source

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


All Articles