[CSS] - position

2017-11-02  本文已影响36人  JellyL

position属性能帮助你控制一个元素的定位。

position的值有以下6种:

举个🌰:

//html
<div class="parent">
  Parent element
<div class="element positions">Child element</div>
</div>
//css
.parent {
  border: 2px solid #0074d9;
  color: #0074d9;
  padding: 20px;
}

.element {
  border: 1px dotted #000;
  background-color: #eee;
  padding: 20px;
  color: #000;
  margin-top: 10px;
}

body, html {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

以上代码为postion 默认为static,其结果如图:

static

在css 文件中修改 . positions样式为:

. positions {
  position: relative;
  left: 30px; 
  top: 30px;
}

其结果如图:


relative

在css 文件中修改 .element样式为:

. positions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

其结果如图:


absolute

在css 文件中修改 .element样式为:

. positions {
  position: fixed;
  left: 30px; 
  top: 30px;
}

其结果如图:


fixed

在css 文件中修改 .element样式为:

. positions {
  position: sticky;
  top: 50px;
}

当页面足够长,并且child element滑动到离document顶端的50px时,child element将固定在top:50px的位置。

sticky.gif

绝对定位元素通常以相对定位元素为容器块

absolute child element and relative parent element

如果父元素不是relative,那么结果会是这样的:

absolute child element and static parent element
上一篇 下一篇

猜你喜欢

热点阅读