如何用相对位置包装内部div?

时间:2019-01-07 09:22:09

标签: css

我有一个外部和内部盒子,位置设置为相对。我想要的应该是这样的:

enter image description here

代码是:

body {
  background-color: lightblue;
  width: 100%;
  height: 100%;
}

.outerbox {
  position: relative;
  float: left;
  left: 30px;
  top: 50px;
  background: orange;
  border: 2px solid red;
}

.innerbox {
  position: relative;
  float: left;
  width: 100px;
  height: 50px;
  margin-left:100px;
  margin-top:100px;
  background: green;
  border: 2px solid red;
}
<body>
  <div class="outerbox">
    <div class="innerbox">
    </div>
  </div>
</body>

是否可以通过margin:0获得相似的结果,并且仅更改top中的leftinnerbox值?

采用这种样式,外部div不再包裹内部框:

CSS

.innerbox {
    position: relative;
    float: left;
    width: 100px;
    height: 50px;
    margin: 0;
    left: 100px;
    top: 100px;
    background: green;
    border: 2px solid red;
}

enter image description here

谢谢。

*更新*

我想补充一点,我不想固定外箱的高度。谢谢。

3 个答案:

答案 0 :(得分:1)

Is it possible to get a similar result with margin:0 and changing only top and left values in innerbox?

Not really.

Relative positioning moves an element from it’s “default” position that it would normally have - but it keeps the original space it would have required reserved, it does not make it “take” the space at the position it was moved to. So while you can move the inner element to the place you want it, it will not make the outer element “grow” accordingly.

I don't want ("mis")use margin for positioning the inner div

Don’t worry about the “semantics of CSS” too much here … There is often more than one way to achieve a desired optical result, and seldom one way is “wrong” and the other one “right”.

As long as the solution you have achieves what you want, and is not hindered by other restrictions - use it!

答案 1 :(得分:0)

当外箱具有position: relative时,您可以将position: absolute用作.innerbox,以便为.outerbox赋予尺寸(宽度和高度),并且可以使用{{ 1}}和top将内部矩形放置在您想要的每个位置上...

left
body {
  background-color: lightblue;
  width: 100%;
  height: 100%;
}

.outerbox {
  position: relative;
  width:200px;
  height:100px;
  left: 30px;
  top: 50px;
  background: orange;
  border: 2px solid red;
  
}

.innerbox {
  position: absolute;
  
  width: 100px;
  height: 50px;
  left:98px;
  top:48px;
  background: green;
  border: 2px solid red;
}

答案 2 :(得分:0)

希望这会对您有所帮助。

body {
  background-color: lightblue;
  width: 100%;
  height: 100%;
}

.outerbox {
  position: relative;
  float: left;
  left: 30px;
  top: 50px;
  background: orange;
  border: 2px solid red;
  height:200px;
  width:300px;
}


.innerbox {
    position: absolute;
    float: left;
    width: 100px;
    height: 50px;
    margin: 0;
  /*left: 100px;
    top: 100px; */
    bottom:0;
    right:0;
    background: green;
    border: 2px solid red;
}
<div class="outerbox">
    <div class="innerbox">
    </div>
  </div>