如何使用jQuery将<div>置于另一个底部?</div>

时间:2011-08-19 15:17:53

标签: jquery layout html

我想做这样的事情:

http://i56.tinypic.com/rlj2w3.png

比例只是为了说明,但您可以使用它们。

我想采用小红色<div>框并将其附加到绿色<div>框的底部。

两个盒子的宽度都很小 - &gt;为200px;大 - &gt; 600px的;

我怎样才能使用javascript(jQuery)?

4 个答案:

答案 0 :(得分:2)

<强> 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 */
}

小提琴:http://jsfiddle.net/g6fKg/


如果您的小DIV不在您的大DIV中,您将不得不求助于使用Javascript:

var $big = $('#big'),
    $small = $('#small');

$small.css({
    top: $big.offset().top + $big.height() - $small.height(),
    left: $big.offset().left + ( ($big.width() - $small.width()) / 2 )
});

这还有一个额外的好处,就是不要求你知道你的DIV的大小。

而且,这是小提琴:http://jsfiddle.net/g6fKg/14/

答案 1 :(得分:1)

如果您的代码布局如下:

<div class="container">
  <div class="small">Small</div>
  <div class="large">Large</div>
</div>

您可以使用此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.

答案 2 :(得分:1)

你可以尝试这个解决方案,它不会设置任何left样式来居中较小的div,它基本上取决于外部div宽度。这个解决方案并不关心外部div的宽度或内部div的宽度,因为我使用margin:auto来完美地对齐元素

正在使用 demo

Demo 在较大的div之外使用较小的div

标记

<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;
}

答案 3 :(得分:0)

如果您想在大方框中“添加”div,请使用after方法:

   $('#big').after('<div id="small"></div>');

检查出来:http://api.jquery.com/after/

但是,如果两个框已经在标记中:

<html>
 <div id="big" />
 <div id="small />
</html>

我会使用appendTo(http://api.jquery.com/appendTo

$("#small").appendTo("#big");

我假设您已经为此创建了CSS,但如果没有,您可以查看使用Jquery将div居中的这个问题: Using jQuery to center a DIV on the screen

同时检查Jquery CSS以使用Jquery更改元素的样式:http://api.jquery.com/css/