元素高度基于百分比

时间:2013-12-24 00:50:17

标签: html css css3

所以我一直在试验div,试图抓住整个页面布局。我在所有这些上放了1px边框,这样我就能看出我的css如何影响它们。我有点困惑。我知道将任何属性设置为百分比会使该属性根据其容器的大小计算。 (如果我弄错了,请纠正我。我还在学习所有这些。)

但就div高度而言,我认为将其设置为百分比(没有容器)会使高度依赖于内容,因为您从未指定过高度。但是,我将div高度设置为100%,它似乎有一个预定的高度。我会发布代码。

HTML 忽略脚本链接。一旦我掌握了布局的东西,我就会继续使用Javascript。

<!DOCTYPE>
<html>
<head>
    <script type="text/javascript" src="jQuery.js"></script>
    <script type="text/javascript" src="scripttwo.js"></script>
    <link type="text/css" rel="stylesheet" href="styletwo.css"/>
    <title>Messing With Div's</title>
</head>
<body>

<div id=one></div>
<div id=two></div>
<div id=three>
    <div id=four></div>
    <div id=five></div>
    <div id=six></div>
</div>

</body>
</html>

CSS

body
    {margin:0px;}

div
    {border:1px solid black;
    box-sizing:border-box}

#one
    {width:96%;
    height:100px;
    margin:auto;
    margin-top:30px}

#two
    {width:40%;
    height:500px;
    margin-left:2%;
    margin-top:2%;
    display:inline-block;
    margin-bottom:30px}

#three
    {width:54%;
    margin-top:2%;
    margin-right:2%;
    display:inline-block;
    float:right}

#four
    {width:90%;
    height:20%;
    margin:auto;
    margin-top:10%;
    border:1px solid red;
    display:static}

#five
    {width:90%;
    height:20%;
    margin:auto;
    margin-top:10%;
    border:1px solid red;
    display:static}

#six
    {width:90%;
    height:20%;
    margin:auto;
    margin-top:10%;
    margin-bottom:10%;
    border:1px solid red;
    display:static}

3 个答案:

答案 0 :(得分:1)

#one#two显然会分别具有100px和500px的预定高度。

#three一开始没有任何高度,因为其中没有任何内容,并且未在css或html中设置高度。但是,当你将下面的三个div加入其中时,它的高度为2px + margin-top + margin - 其中三个div的底部......

#four, #five, and #six每个的高度应该只有2像素。因为它们中没有任何东西,它们的高度是#three的20%(这是0)所以20%是0.边框在div的每一边增加1px,所以顶部和底部增加了高度。就像我说的那样,每个人的可见高度都是2px。

答案 1 :(得分:1)

我明白了。它与HTML版本有关。我将“!doctype”更改为“!doctype html”,并修复了它。无论它之前使用什么版本,显然有div“绕过”他们的容器,因为它没有为它设置高度。定义高度的下一个容器是body,其高度是窗口高度。当我添加“html”时,我得到了与jsfiddle相同的结果。

编辑:我发现它是“绕过”容器的原因是因为一旦我为#three定义了一个特定的高度,那么其他人就会正确地调整它们的大小。

编辑2:现在,我放在#three之外的一个div(也设置为20%)与#three中的div(只是一行)相同。所以,我认为“身体”的高度是未定义的,无论它之前使用的任何版本设置为窗口高度?

答案 2 :(得分:0)

您在div #four#five#six中指定了边距,因此高度取决于您的内容,正好是margin的10%到顶部和10%基于容器宽度

详细信息:http://www.w3schools.com/css/css_margin.asp

  

%指定包含元素宽度百分比的边距

点击此处,您的布局没有marginhttp://jsfiddle.net/23HcY/

#four
{
  width:90%;
  height:20%;
  margin:auto;
  margin-top:0%;
  border:1px solid red;
  display:static
}

#five
{
  width:90%;
  height:20%;
  margin:auto;
  margin-top:0%;
  border:1px solid red;
  display:static
}

#six
{
  width:90%;
  height:20%;
  margin:auto;
  margin-top:0%;
  margin-bottom:0%;
  border:1px solid red;
  display:static
}