CSS position定位

192 阅读1分钟

CSS 中的 position 属性用来设置元素在页面中的位置,通过该属性可以把任何属性放置在任何你认为合适的位置。

1. 相对定位:relative

相对定位就是元素相对于自己默认的位置来进行位置上的调整,可以通过 top、bottom、left 和 right 四个属性的组合来设置元素相对于默认位置在不同方向上的偏移量。

<!DOCTYPE html>
<html>
<head>
    <style>
        div{
            border: 1px solid black;
        }
        div.static {
            width: 140px;
            height: 50px;
            background-color: #B3FF99;
            line-height: 50px;
            text-align: center;
            position: relative;
            top: 25px;
            left: 10px;
        }
        p {
            width: 100px;
            height: 100px;
            background-color: #CCC;
            margin: 0;
        }
    </style>
</head>
<body>
    <div>
        <div class="static">position: relative;</div>
        <p></p>
    </div>
</body>
</html>

2. 绝对定位:absolute

绝对定位就是元素相对于第一个非静态定位(static)的父级元素进行定位,如果找不到符合条件的父级元素则会相对与浏览器窗口来进行定位。同样可以使用 top、bottom、left 和 right 四个属性来设置元素相对于父元素或浏览器窗口不同方向上的偏移量。

<!DOCTYPE html>
<html>
<head>
   <style>
       div{
           border: 1px solid black;
           position: relative;
       }
       div.static {
           width: 150px;
           height: 50px;
           background-color: #B3FF99;
           line-height: 50px;
           text-align: center;
           position: absolute;
           bottom: 10px;
           right: 5px;
       }
       p {
           width: 100px;
           height: 100px;
           background-color: #CCC;
           margin: 0;
           text-align: center;
           line-height: 100px;
       }
   </style>
</head>
<body>
   <div>
       <div class="static">position: absolute;</div>
       <p>&lt;p&gt;</p>
   </div>
</body>
</html>

3、固定定位:fixed

固定定位就是将元素相对于浏览器窗口进行定位,使用固定定位的元素不会因为浏览器窗口的滚动而移动,就像是固定在了页面上一样,我们经常在网页上看到的返回顶部按钮就是使用固定定位实现的。

<!DOCTYPE html>
<html>
<head>
    <style>
        div{
            height: 500px;
        }
        p {
            width: 150px;
            height: 50px;
            background-color: #CCC;
            margin: 0;
            text-align: center;
            line-height: 50px;
            position: fixed;
            right: 20px;
            bottom: 20px;
        }
    </style>
</head>