对绝对定位和相对定位的理解

包裹性

  • 该元素设置了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>
相关文章
相关标签/搜索