在div元素中创建完美匹配的页眉和页脚元素

  • 本文关键字:元素 div 创建 完美 html css
  • 更新时间 :
  • 英文 :


我正在尝试用css制作页眉和页脚。以下是我的代码:

HTML

<div id="container">
    <div id="header">Kaboom!</div>
    <div id="footer">Kaboom!</div>
</div>

CSS

#header{
    background-color:orange;
    width:500px;
    height:20px;
    border:3px solid blue;
    border-left-style:none;
    border-right-style:none;
    list-style-type:none;
    border-top-style:none;
    text-align:center;
}
#footer{
    margin-top:455px;
    background-color:pink;
    width:500px;
    height:20px;
    border:3px solid blue;
    border-left-style:none;
    border-right-style:none;
    list-style-type:none;
    border-bottom-style:none;
    text-align:center;
}
#container
{
    margin:auto;
    background-color:#addadd;
    width:500px;
    height:500px;
    border:5px solid blue;
    border-radius:5px;
}

jsfiddle

虽然我的代码运行良好,但页眉位于顶部,页脚位于底部。但我必须手动做很多事情,例如,我必须从内部元素中删除边界,同样,我必须通过构建和尝试方法设置边距。我的问题是,这里是否存在一些数学问题,即如果容器的高度和宽度是500px,那么为了固定其中的元素,它们应该相对于容器有一些正负像素。类似地,页眉应该放在什么边距,页脚应该放在相对于容器的什么边距,或者有其他有效的方法吗?

这个怎么样,position:相对于#容器,然后position:绝对于页脚和页眉。

#container {
    position: absolute;
    margin:auto;
    background-color:#addadd;
    width:500px;
    height:500px;
    border:2px solid blue;
}
#header {
    position: absolute;
    background-color:orange;
    top: 0;
    width:500px;
    height:20px;
    border-bottom: 2px solid blue;
    text-align:center;
}
#footer {
    position: absolute;
    bottom: 0;
    background-color:pink;
    border-top: 2px solid blue;
    width:100%;
    height:20px;
}

jsfiddle

最新更新