【CSS基础】position 属性

121 阅读1分钟

position属性的各种值

static

.static {
    position: static;
}

static 属性是默认值,一个 position: static 的元素表示它不会被"positioned",当 position 被设为其它值时表示会被"positioned"

relative

.relative1 {
    position: relative;
    /*style*/
    width: 540px;
    border: 5px solid #d3e0f3;
    padding: 20px;
}
.relative2 {
    position: relative;
    top: -20px;
    left: 20px;
    /*style*/
    width: 500px;
    border: 5px solid #f3d3e7;
    padding: 20px;
    background-color: white;
}        

image.png

fixed

/*一个固定在左上角的元素*/
.fixed {
    pisition: fixed;
    top: 0;
    left: 0;
    width: 200px;
}

一个固定定位元素会相对于视窗来定位,即便页面滚动,它还是会留在相同的位置,和 relative 一样,它也有 toprightbottomleft属性可用。

absolute

absolutefixed 的表现类似,但是它不是相对于视窗,而是相对于最近的"positioned"祖先元素定位。如果一个绝对定位的元素没有"positioned"祖先元素,则它会相对于文档的 body 元素进行定位,并且会随着页面的滚动而滚动。

.relative {
    position: relative;
    width: 500px;
    height: 200px;
}

.absolute {
    position: absolute;
    top: 700px;
    left: 0;
    width: 300px;
    height: 100px;
}

image.png