2012-08-13 25 views
2

我有一个标题,应始终显示在页面的顶部约20像素从顶部。 现在它被定义为两个div,并按照它应有的方式工作。嵌套两个div在“标题”div打破设计

http://jsfiddle.net/nBgj4/

<!DOCTYPE html> 
<html> 
<head> 
<style type="text/css"> 
body { 
    height: 100%; 
    margin-left: 20px; 
    margin-top:0px; 
    margin-bottom: 0px; 

} 
.subheader-left { 
    position: absolute; 
    top: 20px; 
    font-family: serif; 
    font-size: 20px; 
    text-align: left; 
} 
.subheader-right{ 
position: absolute; 
font-family: sans-serif; 
font-size: 12px; 
top: 20px; 
right: 20px;} 
</style> 

<title>XYZ</title> 

</head> 
<body> 
    <div class="subheader-left">XYZ<br /></div> 
    <div class="subheader-right">LOREM</div> 
</body> 
</html> 

当我尝试用“头” DIV标签封装两个DIV标签和分配给它两个封装的div有共同的元素(顶:20像素),它打破了设计。

我总是认为嵌套的div继承自他们的父div,并且想明白为什么在这种情况下这不起作用。我认为这是因为“位置:绝对”标签,但“位置:相对”打破了设计。

感谢

http://jsbin.com/emulel/1/edit

<!DOCTYPE html> 
<html> 
<head> 
<style type="text/css"> 
body { 
    height: 100%; 
    margin-left: 20px; 
    margin-top:0px; 
    margin-bottom: 0px; 

} 
.header {top:20px;} 
.subheader-left { 
    position: relative; 
    font-family: serif; 
    font-size: 20px; 
    text-align: left; 
} 
.subheader-right{ 
position: relative; 
font-family: sans-serif; 
font-size: 12px; 
right: 20px;} 
</style> 

<title>XYZ</title> 

</head> 
<body> 
<div class="header"> 
    <div class="subheader-left">XYZ<br /></div> 
    <div class="subheader-right">LOREM</div> 
</div> 
</body> 
</html> 
+0

请在jsFiddle.net上发帖。使我们所有人都更轻松,更轻松 – 2012-08-13 21:35:39

+0

also ..'position:absolute'使元素具有相对于根的距离属性元素含义'top:20px'从屏幕顶部始终为20px,无论它嵌套的位置 – 2012-08-13 21:37:39

+0

@MattHintzke实际上'top:20px'在这里什么都不会做,'couse'。header'默认位置为'static' – 2012-08-13 21:41:24

回答

2

你混了几个东西:

标题没有指定位置,所以顶:20px的;没用。如果你定位元素,绝对将始终定位在相对定位的元素上。

你应该去浮动:

保持你的HTML喜欢它,并添加这个CSS:

.header { 
    overflow: hidden;/* to contain the floated elements */ 
} 
.subheader-left { 
    float: left; 
}.subheader-right { 
    float: left; 
} 
0

你需要

.subheader-left { 
float:left; 
} 
.subheader-right{ 
float:right; 
} 

这是因为在第一个例子中,该申报单有position:absolute,所以他们的宽度是最小的。

但第二个他们有position:relative和它的displayblock,所以他们扩大,他们的宽度是最大的。然后第二个div进入第二行。

但是,如果你添加浮动,他们的宽度将是最小的,他们将留在同一行。此外,第二个div将向右移动。

但随后记得换头的overflowhiddenautoscroll,或添加<div style="clear:both"></div>在头的末端。