带你走进CSS定位详解

标题图

学习CSS相关知识,定位是其中的重点,也是难点之一,如果不了解css定位有时候都不知道怎么用,下面整理了一下关于定位属性的具体理解和应用方案。

一:定位

定位属性列表

  • position
  • top
  • bottom
  • right
  • left
  • z-index

position

基本语法:

position:static | absolute | fixed | relative

语法介绍:

  1. static:默认值,无特殊定位。
  2. absoulte:相对于其最近的一个定位设置的父对象进行绝对定位,可用left,right,top,bottom。
  3. fixed:生成绝对定位的元素。
  4. relative:生成相对定位的元素,可通过left,right,top,bottom属性设置相对于自身偏移位置。

代码:

div { position:relative; top:-4px } 

bottom

基本特殊:定位元素

基本语法:bottom:auto | length

语法

  1. auto:默认值,无特殊定位。
  2. length:长度值 | 百分比,必须定义position的属性值为absolute或者relative才有效。

代码:

div { position:relative; bottom:6px; }   

z-index

语法:z-index:auto | number
取值:auto:默认值,number:无单位的整数值,可负数。

代码:

div { position:absolute; z-index:5; width:6px; } 

left

基本语法:left:auto | length

  1. auto:默认值,无特殊定位。
  2. length:长度值 | 百分比,必须定义position的属性值为absolute或者relative才有效。

代码:

div { position:relative; top:-3px; left:6px; }   

top

基本语法:top:auto | length

  1. auto:默认值,无特殊定位。
  2. length:长度值 | 百分比,必须定义position的属性值为absolute或者relative才有效。

代码:

div { position:relative; top:-3px; left:5px;}

基本语法:right:auto | length

  1. auto:默认值,无特殊定位。
  2. length:长度值 | 百分比,必须定义position的属性值为absolute或者relative才有效。

代码:

div { position:relative; top:-3px; right:6px}

相对定位

relative生成相对定位的元素,相对于其它位置进行定位。

代码:

<style type="text/css">
        #box1 {
            margin: 10px;
            width: 100px;
            height: 100px;
            background-color: blue;
        }
        #box2 {
            margin: 10px;
            width: 100px;
            height:100px;
            background-color: red;
            /*position: relative;
            left: 100px;
            top: 100px;*/
        }
    </style>

<div id="box1"></div>
<div id="box2"></div>

绝对定位

绝对定位相对于它的参照物移动位置,如果没有,默认为body为参照物。

结语

  • 带你走进CSS定位详解,多试试,熟能生巧嘛~

送❤

猜你喜欢

转载自www.cnblogs.com/dashucoding/p/9415163.html