您好!欢迎访问家园网-www.jy.wang!

家园网

javascript中,元素的position属性有几种定位方式?举例讲解一下

网络 作者:本站 点击:

JavaScript中元素的position属性主要有4种定位方式,每种方式都有不同的布局行为:

四种定位方式对比

定位方式参考基准是否脱离文档流特点
static正常文档流默认值,元素按正常顺序排列
relative自身原始位置相对自身偏移,原位置保留空白
absolute最近的非static父元素完全脱离文档流,不占原位置
fixed浏览器窗口固定位置,滚动时不移动

详细讲解与示例

1. static(静态定位)

  • 默认定位方式,元素按照正常文档流排列

  • top、right、bottom、left和z-index属性无效

2. relative(相对定位)
以自身原始位置为基准进行偏移,原位置仍保留空白:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>相对定位示例</title>
    <style>
        .box {
            display: inline-block;
            width: 100px;
            height: 100px;
            background: red;
            color: white;
            margin: 10px;
            text-align: center;
            line-height: 100px;
        }
        #two {
            position: relative;
            top: 20px;
            left: 20px;
            background: blue;
        }
    </style>
</head>
<body>
    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
</body>
</html>


3. absolute(绝对定位)
相对于最近的非static定位祖先元素定位,完全脱离文档流:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绝对定位示例</title>
    <style>
        .container {
            position: relative;
            width: 400px;
            height: 300px;
            border: 2px solid #333;
            margin: 20px;
        }
        .box {
            width: 100px;
            height: 100px;
            background: green;
            color: white;
            text-align: center;
            line-height: 100px;
        }
        .absolute-box {
            position: absolute;
            top: 50px;
            left: 50px;
            background: orange;
        }
    </style>
</head>
<body>
    <div>
        <div>背景元素</div>
        <div class="box absolute-box">绝对定位</div>
    </div>
</body>
</html>

4. fixed(固定定位)
相对于浏览器窗口定位,滚动时位置不变:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>固定定位示例</title>
    <style>
        .fixed-menu {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 60px;
            background: rgba(0,0,0,0.8);
            color: white;
            text-align: center;
            line-height: 60px;
            z-index: 1000;
        }
        .content {
            margin-top: 80px;
            height: 2000px;
            background: linear-gradient(to bottom, #f0f0f0, #e0e0e0);
        }
    </style>
</head>
<body>
    <div>固定导航菜单</div>
    <div>滚动页面时,顶部菜单始终保持固定</div>
</body>
</html>

实用建议‌:在开发中,通常将父元素设置为position: relative,子元素设置为position: absolute,这样可以创建相对于父元素的精确定位,避免意外的布局问题。


标签: