如何将div置于另一个div中,最简单的方法是什么?

时间:2014-10-12 16:32:55

标签: html css

我试图将一个蓝色的盒子完美地放在它的父div中,我想确保我以最简单的方式做到这一点。我必须做一些简单的数学运算才能知道用什么px设置蓝框的宽度和高度,只想看看是否有更简单的方法。例如,为了使div宽度居中,我可以做“margin:auto”这样的高度是什么?

这是小提琴:http://jsfiddle.net/u2c64b52/

我的css代码如下:

#container {
 width: 500px;
 height: 500px;
 background-color: lightgreen;
 margin: 0 auto;
 position: relative;
}

#box1 {
 width: 50px;
 height: 50px;
 background-color: red;
 position: absolute;
 right: 0;
}

#box2 {
 width: 50px;
 height: 50px;
 background-color: blue;
 margin: auto;
 margin-top: 225px;
 margin-left: 225px;
 position: absolute;    
}

5 个答案:

答案 0 :(得分:3)

最简单的方法? Flexbox的。不适用于IE 10或更低版本,并且我没有包含供应商前缀:

#outer {
  background: red;
  width: 400px;
  height: 400px;
  display: flex; /* These three lines make the magic happen */
  justify-content: center;
  align-items: center;
}
#inner {
  width: 200px;
  height: 200px;
  background: blue;
}
<div id="outer">
  <div id="inner">Lorem ipsum</div>
</div>

答案 1 :(得分:1)

如果您只想将某些文字居中和垂直居中,则应将父 text-align 设置为 center ,并将其 line-height < / strong>至父母的身高

#container {
    width: 500px;
    height: 500px;
    background-color: lightgreen;
    margin: 0 auto;
    line-height: 500px;
    text-align: center;
}

#box1 {
    display: inline;
    width: 50px;
    height: 50px;
}

Demo

答案 2 :(得分:1)

如果容器是相对的:

    #box1 {
      width: 50px;
      height: 50px;
      background-color: red;
      overflow: auto;
      margin: auto;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }

更新了小提琴:http://jsfiddle.net/u2c64b52/3/

答案 3 :(得分:-1)

只需在父框内使用margin: 0 auto;即可。没有数学要求,它将在中心。不需要复杂的东西。确保它是CSS框中唯一的边距属性。

所以这会导致问题...

margin: 0 auto;
margin-left: 10px;
margin: right: 10px;

只是......

margin: 0 auto;

答案 4 :(得分:-2)

你可以在没有CSS的情况下使用jQuery:

var container = $('#container');
$('#container div').each(function () {
    var $this = $(this);
    var top = (container.width() / 2) - $this.width() / 2;
    var left = (container.height() / 2) - $this.width() / 2;
    $this.css({
        top: top,
        left: left
    });
});

Demo