css - 在 "header"div 中嵌套两个 div 会破坏设计

标签 css html

我有一个标题,它应该始终显示在页面顶部距顶部约 20 像素的位置。 现在它是用两个 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 共有的元素(顶部: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/

相关文章:

html - 创建一个固定的侧边栏而不让它脱离流程

jquery - 数据表.net ScrollX |标题和数据列宽度问题

html - 第一个元素菜鸟问题

jquery - 无法弄清楚为什么该页面在 Firefox 中看起来很糟糕?在 Chrome/IE 中看起来不错

javascript - CSS/JavaScript : issue when styling canvas (for mouse drawing)

html - 如何使用 MVC4 从 TempData 解释 HTML?

html - 在方形空间中更改子导航事件链接样式

html - 无法使用 Bootstrap v2.0.4 定义水平表单

值更改时的 HTML 输入

jquery - 从 Bootstrap 表中删除突出显示