對絕對定位和相對定位的理解

包裹性

  • 該元素設置了absolute後,該元素就會具備inline-block的特性
  • inline-block,設置inline-block屬性後,若是該元素沒有設置寬高或者設置寬度和高度爲100%, 則該元素的大小是由其子元素的大小全部決定,所撐起來 見demo2

破壞性

  • 該元素設置爲absolute後,該元素不會撐起其父元素的大小,見demo1

若是該元素的父元素爲相對定位,該元素設置爲絕對定位,而且該元素不設置left,right,top,bottom,使用默認的,若是其父元素中還有其餘非絕對元素,該元素絕對定位是相對於相鄰非絕對定位的元素而言,見下面demo3

  1. demo1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .app0{
        padding: 20px;
        position: relative;

        border: 1px solid red;
    }
    .app1{
        width: 100px;
        height: 100px;
        position: absolute;
        background-color: green;
    }
</style>
<body>
<div class="app0">
    <div class="app1">absolute破壞性,使父元素塌陷</div>
</div>
</body>
</html>
  1. demo2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .app0{
        padding: 20px;
        box-sizing: border-box;
        position: absolute;
        border: 1px solid red;
    }
    .app1{
        width: 100px;
        height: 100px;
        background-color: aqua;
    }

</style>
<body>
<div class="app0">
    <div class="app1"></div>
</div>
</body>
</html>
  1. demo3
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
  *{
    margin: 0;
    padding: 0;
  }
  .app{
    width: 500px;
    height: 500px;
    border: 1px solid red;
    position: relative;
  }
  .app0{
    width: 200px;
    height: 100px;
    position: relative;
    /*position: absolute;*/
    border: 1px solid green;
  }
  .app1{
    width: 300px;
    height: 200px;
    position: absolute;
    border: 1px solid blue;
  }
</style>
<body>
<div class="app">
  <div class="app0"></div>
  <div class="app1"></div>
</div>
</body>
</html>
相關文章
相關標籤/搜索