How to center <div> on the bottom of the other using jQuery?
I would like to do something like this:
The proportions are just for illustration, however you can use them.
I want to take the small red <div>
box and append it to the bottom of the big green <di开发者_开发技巧v>
box.
The width of both boxes is known small -> 200px; big -> 600px;
How can I do this using javascript (jQuery)?
HTML:
<div id="big">
<div id="small"></div>
</div>
CSS:
#big {
width: 600px;
height: 800px;
background: green;
position: relative;
}
#small {
background: red;
width: 200px;
height: 200px;
position: absolute;
bottom: 0; left: 200px; /* (600-200)/2 */
}
Fiddle: http://jsfiddle.net/g6fKg/
If your small DIV is not inside your big DIV, you'll have to resort to using Javascript for this:
var $big = $('#big'),
$small = $('#small');
$small.css({
top: $big.offset().top + $big.height() - $small.height(),
left: $big.offset().left + ( ($big.width() - $small.width()) / 2 )
});
This also has the added benefit of not requiring you to know the size of your DIVs.
And, here's the fiddle: http://jsfiddle.net/g6fKg/14/
If your code is laid out like this:
<div class="container">
<div class="small">Small</div>
<div class="large">Large</div>
</div>
You can do it with this CSS:
.container {
width: 600px;
height: 800px;
position: relative;
margin: 10px auto;
}
.container .large {
position: absolute;
width: 600px;
height: 800px;
background-color: green;
z-index: 1;
}
.container .small {
position: absolute;
bottom: 0;
left: 200px;
z-index: 2;
width: 200px;
height: 200px;
background-color: red;
}
Live demo.
You can try this solution which do not set any left
style to center the smaller div which is basically dependent on the outer div width. This solution doesnt care about outer div's width or innder div's width because I am using margin:auto
which takes care of centering the element perfectly
Working demo
Demo with smaller div outside the bigger div
Mark up
<div id="big">
<div id="small">
<div></div>
</div>
</div>
Css
#big {
width: 600px;
height: 800px;
background: green;
position: relative;
}
#small{
bottom: 0px;
position: absolute;
width: 600px;
}
#small div{
background:red;
height: 200px;
margin: auto;
position: relative;
width: 200px;
}
If you're looking to "add" a div to the big box, use the after method:
$('#big').after('<div id="small"></div>');
Check it out: http://api.jquery.com/after/
However, if both boxes are already in markup:
<html>
<div id="big" />
<div id="small />
</html>
I would use appendTo (http://api.jquery.com/appendTo)
$("#small").appendTo("#big");
I assume you already have your CSS created for this, but if not you can look at this question that uses Jquery to center a div: Using jQuery to center a DIV on the screen
Also check out Jquery CSS to change the style of elements using Jquery: http://api.jquery.com/css/
精彩评论