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

时间:2014-10-28 10:03:21

标签: 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,那么为了固定其中的元素,它们应该具有相对于容器的一些正或负像素。类似地,应该放置标题的边距以及相对于容器放置的边距,还是有其他有效的方法?

1 个答案:

答案 0 :(得分:1)

这个怎么样, position:相对于#container,然后position:absolute到页脚和标题。

#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