页面布局,顶部和底部随屏幕滚动?

页面头部、底部都是使用fixed做固定,目前实现效果如图https://img.mukewang.com/5b8175a10001471b19200977.jpg

整个页面最外层有一个大的div包裹,我将这个包裹div的width:90%;margin:0 auto;

问题①.顶部div的width:100%;position: fixed;此时顶部并没有水平居中(width:100%并没有相对包裹div的width:90%来算),如何让顶部div水平居中显示?

问题②.底部使用fixed,如何使它与页面内容对齐,并且不会出现覆盖页面内容的部分高度(就是图中红色②标记的那块底部的高度)?


以下是html/css代码

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title></title>

    <style>

        body{

            margin: 0;

            padding: 0;

            color: #fff;

        }

        .container{

            width: 800px;

            height: 1000px;

            background: #4c77f2;

            margin: 0 auto;

            padding-top: 40px;

            text-align: center;

        }

        .header{

            width:100%;

            position: fixed;

            height: 40px;

            background: #414141;

            text-align: center;

            font-size: 16px;

            line-height: 40px;


        }

        .footer{

            width: 800px;

            height: 100px;

            background: #333;

            margin: 0 auto;

            text-align: center;

            font-size: 16px;

position:fixed;

bottom:0;


        }

    </style>

</head>

<body>

<div style="margin:0 auto;width:90%;">

    <div class="header">这是页面头部</div>

    <div class="container">

    这是页面内容

    </div>

    <div class="footer">这是页面底部</div>

</div>

    

</body>

</html>


努力奔跑的自己
浏览 1011回答 1
1回答

橋本奈奈未

fixed是相对整个窗口的,width的计算也是,所以如果你要保持和div一样那就设置一样的值。定位之后margin: 0 auto就没用了,可以使用left:50%;transform: translateX(-50%)居中因为定位之后元素脱离的正常的文档流,所以会覆盖到地下的内容,那么可以把地下那个空间留出来即可,margin-bottom,padding-bottom都可以,但是比较好的做法是在fixed元素外层套一层div<footer>     <div>         这个div fixed     </div> </footer>然后高度给的是footer这个元素,而div的height设置为inherit。
打开App,查看更多内容
随时随地看视频慕课网APP