找到div宽度

时间:2013-04-12 15:02:21

标签: css html

我有三个div。两个较小的是在同一个容器内,第三个div。

  • 第一个孩子div是350x350 px big。
  • 第三个div是另一个容器div的89%,这意味着我不知道它的大小。
  • 我想在第一个子div和容器div的边缘之间设置第二个子div。

基本上:

<div id="container">
    <div id="first_child" style="width:350px; height:350px;">&nbsp;</div>
    <div id="second_child" style="width:???px; height:350px;">&nbsp;</div>
</div>

如果我希望second_child元素精确地跨越second_child元素和first_child边缘,我如何计算container元素的宽度?< / p>

编辑: 上传了快速绘制的图像。大黑方是container,测量结果未知。红色框为first_child,蓝色框为second_child。我想找到second_child的宽度,以便从first_child的末尾延伸到container的右边缘。

5 个答案:

答案 0 :(得分:3)

您可以使用CSS calc()

#second_child {
   width: -moz-calc(100% - 350px);
   width: -webkit-calc(100% - 350px);
   width: calc(100% - 350px);
}

对于IE8及更低版本,你必须使用jQuery或javascript

答案 1 :(得分:2)

我认为你需要的是使用像这样的css:

#container {
    width:89%;
    height:350px;
}
#first_child {
    float:left;
    width:350px;
    height:350px;
}
#second_child {
    height:350px;
    margin-left:350px;
}

Here is a working example(添加样式以查看效果)

答案 2 :(得分:1)

上面给出了纯CSS的一个很好的答案,所以我只回答“如何找到所需宽度?”的问题。在javascript。

// This is assuming there is no padding.
totalWidth = document.getElementById('container').offsetWidth;
firstChildWidth = document.getElementById('first_child').offsetWidth;
document.getElementById('second_child').style.width = (totalWidth - firstChildWidth) + 'px';

答案 3 :(得分:0)

使用jQuery:

var containerWidth = $('#container').width();
$('#second_child').width(containerWidth - 350);

答案 4 :(得分:0)

你可以用纯css定位来做到这一点,因为你知道第一个孩子有多大:

#container {
position:relative
}

#first_child {
width:350px;
height:350px
}

#second_child {
height:350px;
position:absolute;
top: 0;
left:350px;
right:0;
}

请注意,容器div的位置为:relative。这是制作位置所必需的:绝对使用容器div的左上角而不是正文。