我有一个标题,它应该始终显示在页面顶部距顶部约 20 像素的位置。 现在它是用两个 div 定义的,并按照预期的方式工作。
<!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 共有的元素(顶部:20px),它就会破坏设计。
我总是假设嵌套的 div 继承自其父 div,并想了解为什么这在这种情况下不起作用。我认为这是因为“position:absolute”标签,但“position:relative”破坏了设计。
谢谢
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>
最佳答案
你混淆了一些东西:
header 没有分配位置,所以 top: 20px;是没用的。如果您定位元素,绝对定位将始终针对相对定位的元素定位。
你应该选择 float :
保持 html 不变并添加此 CSS:
.header {
overflow: hidden;/* to contain the floated elements */
}
.subheader-left {
float: left;
}.subheader-right {
float: left;
}
关于css - 在 "header"div 中嵌套两个 div 会破坏设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11942668/