【问题标题】:Parent and child div next to each other without using position:absolute父子 div 相邻而不使用 position:absolute
【发布时间】:2014-06-26 14:09:08
【问题描述】:

有没有一种方法可以在不使用 position:absolute 的子元素的情况下将父元素和子元素彼此相邻放置(就好像它们不是父元素和子元素并且向左浮动一样)?父子元素都应该具有相对于祖父元素的动态宽度。

HTML

<div id="grandparent">
   <div id="parent">
      <div id="child">
      </div>
   </div>
</div>

CSS

#grandparent {
width: 500px;
height: 250px;
border:1px solid #000;
}
#parent {
width: 10%; /* relative to grandparent */
height: 100%;
background-color:red;
}
#child {
width: 90%; /* relative to grandparent */
height: 100%;
background-color:green;
}

我不想使用 jquery。 JavaScript 会没问题。最后,它应该看起来好像父母和孩子都是“祖父母”元素的孩子并且向左浮动。

提前致谢!

【问题讨论】:

  • 使用 JS 来做到这一点首先要删除 position:absolute。如果需要计算宽度,用JS就行了。
  • 也许这就是你想要的jsfiddle.net/L3cxP,注意#child的宽度应该是#parent的9倍,所以应该是900%(不是90%) .
  • 你在找这个jsfiddle.net/5kKnp

标签: html css position


【解决方案1】:

所以我使用 css 完成了这项工作,并附上了 fiddle。基本上,我将#child 元素设为其父元素的 900%,并为其设置了父元素宽度的margin-left,因此它们不会重叠。希望这会有所帮助!

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,您应该使 #child#parent9 倍,因为您将 #parent 宽度设置为 10%

    变化:

    width: 90%; /* relative to grandparent */
    

    width: 900%; /* relative to grandparent */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      相关资源
      最近更新 更多