首页 文章

如何使绝对定位的div的宽度等于它的父级减去一些余量

提问于
浏览
26

我希望有一个内部div,它位于不同大小的容器div中,并从固定的左侧位置开始,然后有一个宽度填充容器的其余部分 . 我在下面包含了一些示例css,试图明白这一点 .

我必须使用绝对定位,所以不能只是向右浮动并设置左边距 . 有关如何使用绝对定位工作的任何想法?我也试过宽度:自动和一些不同的盒子大小选项 .

为了澄清,这方面的棘手问题是必须修复左边框,左边框必须与容器的右边框相对 . 我不能使用position:relative和javascript,但我可能最终会在执行此操作之前将.inner1和.inner2 div设为硬编码宽度 . 但希望避免这种情况 .

.container1 {
  position: relative;
  width: 400px;
  height: 300px;
}

 .container2 {
  position: relative;
  width: 500px;
  height: 300px;
}

.inner {
  position: absolute;
  top: 0px;
  left: 200px;
  height: 100%;
  width: 100%;
}

enter image description here

3 回答

  • 2

    只需指定所有 topleftbottomright 属性,该框将展开以显示所有这些点 .

    .container {
      position: relative;
      width: 400px;
      height: 300px;
    }
    
    .inner {
      position: absolute;
      top: 0;
      left: 200px;
      bottom: 0;
      right: 0;
    }
    

    See the jsFiddle.

  • 56

    我不知道你到底需要什么,但为什么不使用百分比?

    代替:

    .inner {
      position: absolute;
      top: 0px;
      left: 200px;
      height: 100%;
      width: 100%;
    }
    

    你为什么不用这样的东西:

    .inner {
      position: absolute;
      top: 0px;
      left: 50%;
      height: 100%;
      width: 50%;
    }
    

    相应地设置left和width属性的百分比 . 40-60,30-70等 .

    希望这可以帮助 . 如果没有,请说明一点 .

    问候

  • 0

    这很有效 . 将外框的宽度更改为您想要的任何内容,并且内框增长以匹配它 .

    .container {
        width: 400px;
        height: 300px;
    } 
    
    .inner {
        position: relative;
        margin-left: 200px;
        height: 100%;
    }
    

    编辑:here's a fiddle

相关问题