美文网首页
css布局-绝对定位

css布局-绝对定位

作者: 落崖惊风yxy | 来源:发表于2017-07-10 18:52 被阅读0次

position:absolute;
绝对定位脱离了标准文档流,有四个方向:left,right,top,bottom。

1、不针对于祖先元素的参考点
有top参与的情况:参考点是页面的左上角或者右上角。
有bottom参与的情况:参考点是首屏的左下角或者右下角。


图片2.png

2、针对祖先元素的定位参考元素
参考元素:距离最近的且有定位的祖先元素。
参考顶点:参考元素的border以内(背景的四个顶点),无视父盒子的padding。

3、压盖效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .box{
            width: 300px;
            height: 300px;
            padding: 50px;
            border: 1px solid #000;
            position: relative;
        }
        .box .son1{
            width: 300px;
            height: 300px;
            background-color: pink;
        }
        .box .son2{
            width: 200px;
            height: 30px;
            bottom: 100px;
            background-color: green;
            position: absolute;
            left:50%;
            margin-left: -100px;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="son1"></div>
        <div class="son2"></div>
    </div>
</body>
</html>
clipboard.png

第二步:拉回自身宽度的一半 margin:-50%(绝对定位盒子实际占有宽度的一半,使用像素表示法)

.box .son2{
    width: 200px;
    height: 30px;
    bottom: 100px;
    background-color: green;
    position: absolute;
    left:50%;
    margin-left: -100px;
    }
clipboard.png

5、应用
“子绝父相”:子盒子设置为绝对定位,父盒子设置为相对定位。(也有子绝父绝、子绝父固)
因为相对定位结构比较固定,作为绝对定位的参考盒子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        .nav{
            width: 960px;
            height: 50px;
            margin: 20px auto;
        }
        ul{
            list-style: none;
        }
        .nav ul li{
            float: left;
            width: 120px;
            height: 50px;
            line-height: 50px;
            position: relative;
        }
        .nav ul li a{
            text-decoration: none;
            display: block;
            width: 120px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            background-color: green;
            color:#fff;
        }
        .nav ul li a:hover{
            border-top: 5px solid orange;
            position: absolute;
            top:-5px;
        }
    </style>
</head>
<body>
    <div class="nav">
        <ul>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
            <li><a href="">首页</a></li>
        </ul>
    </div>
</body>
</html>

相关文章

网友评论

      本文标题:css布局-绝对定位

      本文链接:https://www.haomeiwen.com/subject/ddsuhxtx.html