代码改变世界

CSS深入了解之absolute绝对定位/relative相对定位

2017-02-27 23:09  SiestaKc  阅读(624)  评论(0编辑  收藏  举报

 

Absolute绝对定位部分


 

一、absolute的概念:

    absolute是相对于最近它的那个已定位的祖先元素定位的,如没有已定位的祖先元素,则相对于初始包含块(body)定位的。

我们一直认为absolute必须搭配relative才能被使用,事实上,

  • relative和absolute是分离,对立的。

  • 独立的absolute可以摆脱overflow限制,无论是滚动的还是隐藏的。

(当元素设置绝对定位后,

其父元素的overflow:scroll; 堆砌没有任何影响。

而当父元素设置position:relative; overflow:hidden; 那么该元素position:absolute;则失去了作用。)

  • 与relative不同的是,absolute与float元素的一样,位置与文档流无关,也因此不占据空间。

      (绝对定位会将该元素从文档中拉出来,相当于将该元素标签先从文档中删除,当元素position:absolute化时,这个元素会根据第一个定义了position的父元素 (static元素除外 ) 进行top、left、right进行定位,可能会覆盖其他元素来进行定位。)

      如果父元素都不满足,则相对于body元素生成一个新的块。

 

二、absolute的特性:

  • 去浮动:

 

 

当第二张图片设置float:left后,【点击第2张图片应用position:absolute变天使】可以去浮动属性,

绝对定位元素脱离文档流,覆盖住第3张图片。

当第二张图片设置position:absolute属性后,float属性将失效(脱离文档流不占据空间)

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绝对定位1</title>
    <style type="text/css">
        input[type=button]  {
            height: 32px;
            width: 100%;
        }
        body div {background-color: #CCC;}
        p{ margin-left: 260px; }
        img+p{ margin-top: 60px; }
    </style>
</head>
<body>
<!--     /*绝对定位会先将该元素从文档中拉出来,也就是相当于将该元素从代码中删除第二个img标签一样,当该元素absolute化时,这个元素会根据第一个定义了定位方式的非static方式的父元素,进行top,left,right进行定位,可能会覆盖其他元素来进行定位。
    (如果不满足,则相对与body元素生成一个新的块。)*/ -->
<!--              <img src="img/刺绣.jpg">
    <img src="img/刺绣1.jpg">
    <img src="img/刺绣2.jpg">
    <p><input type="button" id="button" value=
    "点击第2张图片应用position:absolute变天使"></p>
    <script type="text/javascript">
      var button = document.getElementById("button");
            image2 = document.getElementsByTagName("img")[1];

            if(button && image2){

                 var value_init = button.value;
                 button.onclick = function() {
                     if(this.value == value_init){
                         image2.style.position = "absolute";
                         this.value = "撤销";
                     }else {
                         image2.style.position = " ";
                         this.value = value_init;
                     }
                 };

            } -->



<!-- // absolute的表现特性之一:去浮动
<img src="img/刺绣.jpg">
    <img src="img/刺绣1.jpg">
    <img src="img/刺绣2.jpg">
    <p><input type="button" id="float" value="点击第二张图片应用float:left"></p>
    <p><input type="button" id="button" value=
    "点击第2张图片应用position:absolute变天使"></p>

    <script type="text/javascript">
    var flbtn = document.getElementById("float"),
        button = document.getElementById("button"),
        image2 = document.getElementsByTagName("img")[1];
    if (flbtn && button && image2) {
        var value_init = button.value;
        button.onclick = function() {
            if (this.value == value_init) {
                image2.style.position = "absolute";
                this.value = "撤销";
            } else {
                image2.style.position = "";
                this.value = value_init;
            }
        };
        
        flbtn.onclick = function() {
            image2.style["cssFloat" in this.style? "cssFloat": "styleFloat"] = "left";
        };
    }
    </script> -->


<!--     absolute表现特性二:位置跟随 -->
<img src="img/刺绣.jpg">
<div><img src="img/刺绣1.jpg"></div>
<img src="img/刺绣2.jpg">
<p><input type="button" id="block" value="点击第二张图片应用display:block"></p>
<p><input type="button" id="button" value=
"点击第2张图片应用position:absolute变天使"></p>

<script type="text/javascript">
var  block = document.getElementById("block");
       button = document.getElementById("button");
       image2 = document.getElementsByTagName("img")[1];

             if(block && button && image2){

           var value_button_init = button.value;
           button.onclick = function(){
               if(this.value == value_button_init){
                   image2.style.position = "absolute";
                   this.value = "撤销";
               } else {
                   image2.style.position = " ";
                   this.value = value_button_init;
               }

             };

             var value_block_init = block.value;
           
           block.onclick = function(){
               if(this.value == value_block_init){
                   image2.style.display = "block";
                   this.value = "撤销";
               } else {
                   image2.style.display = " ";
                   this.value = value_block_init;
                        }
                        };
       }


</script>
           

</body>
</html>
源码
  • 位置跟随:

            |Tips|:外层元素不使用相对定位,直接对里面的元素使用absolute定位,然后使用margin来精确定位,实现相对定位的效果。

    /*跟随特性可以更好的实现自适应效果*/

<!------------HTML代码------------->

            <h3 class="nav-list">
                 <a href="#" class="nav-a">
                 求课<i class="icon-hot"></i></a>
            </h3>

<!------------CSS样式表------------->

 .icon-hot {
          position: absolute; 
          width: 28px;  
          height: 11px;
          margin: -6px 0 0 2px;   //上浮效果
          background: url(img/hot.gif); 
}


 

/*   注释<!--
                    -->是为了增强代码的可读性  同时也不影响图片与文字的无缝连接(消除空格)
注释的原因:消除图片和i标签的空格(一般是为了代码结构的整洁性,添加的回车换行)*/

<!----------------------HTML代码------------------>

<div class="course-list-img">
                <span class="icon-recom">推荐</span>
                <img src="img/53d74f960001ae9d06000338-300-170.jpg" width="280" height="160" alt="分享:CSS深入理解之float浮动"><!--
                --><i class="icon-vip">vip</i>
 </div>

<!----------------------CSS代码------------------>

.icon-recom {
        position: absolute; 
        line-height: 20px; 
        padding: 0 5px;
        background-color: #f60; 
        color: #fff; 
        font-size: 12px;
    }

.icon-vip { 
         position: absolute; 
         width: 36px; 
         height: 36px; 
         margin-left: -36px;
         background: url(img/vip.gif); 
         text-align: -9em; 
         overflow: hidden;       
   }
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图标定位二三事</title>
    <style type="text/css">
        body { font: 14px/1.4 "Microsoft YaHei" ; background-color: #EDEFF0;}
        body, h3, h5 {margin:0;}
        img {border: 0 none; vertical-align: bottom;}
                          
        .l {float: left;} .r{float: right;}
                          .constr {width: 1200px; margin-left: auto; margin-right: auto;}
                          .header {background-color: #2A2C2E;}
                          .nav { height: 60px;}
                          .nav-list { float: left; font-size: 14px; font-weight: 400; }
                          .nav-a {display: inline-block; line-height:20px; padding: 20px 35px; color: #B5BDC0; text-decoration: none;}
                          .nav-a:hover{color: #fff;}

                          .course{ padding-top: 10px; }
                          .course-list{ float: left; width: 280px; height: 240px; margin: 5px 10px 15px; border-radius: 0 0 1px 1px; background-color: #F7FAF9; background-color: rgba(255,255,255,1); box-shadow: 0 1px 2px #c5c5c5; text-decoration: none; }
                          .course-list-img { background-color: #6396F1; }
                          .course-list-h { line-height: 50px; font-size: 14px; font-weight: 400; color: #363d40; text-align: center; }
                          .course-list-tips {margin: 0 14px; font-size: 12px;  color: #b4bbbf; overflow: hidden;}

                          .icon-hot {position: absolute; width: 28px; height: 11px; margin: -6px 0 0 2px; background: url(img/hot.gif); }
                          .icon-recom {
                                               position: absolute; 
                                               line-height: 20px; 
                                               padding: 0 5px;
                                                background-color: #f60; 
                                                color: #fff; 
                                                font-size: 12px;
                                             }

                          .icon-vip { 
                                          position: absolute; 
                                          width: 36px; 
                                          height: 36px; 
                                          margin-left: -36px;
                                           background: url(img/vip.gif); 
                                           text-align: -9em; 
                                           overflow: hidden;       
                                        }



    </style>
</head>
<body>
    <div class="header">
        <div class="constr">
               <div class="nav">
             <h3 class="nav-list">
                 <a href="#" class="nav-a">课程</a>
             </h3>         
             <h3 class="nav-list">
                 <a href="#" class="nav-a">问答</a>
             </h3>
                  <h3 class="nav-list">
                 <a href="#" class="nav-a">
                 求课<i class="icon-hot"></i></a>
                      </h3>
                </div>
         </div>
    </div>

    <div class="main">
        <div class="constr">
            <a href="#" class="course-list">
            <div class="course-list-img">
                <span class="icon-recom">推荐</span>
                <img src="img/53d74f960001ae9d06000338-300-170.jpg" width="280" height="160" alt="分享:CSS深入理解之float浮动"><!--
                --><i class="icon-vip">vip</i>
            </div>

            <h5 class="course-list-h">分享:CSS深入理解之float浮动</h5>

            <div class="course-list-tips">
                <span class="l">已完结</span>
                <span class="r">3514人学习</span>    

            </div>
            </a>
        </div>
    </div>
</body>
源码

 

三、absolute与width/height,以及top、bottom等之间关系

  • absolute与width和height

       当内部元素position:absolute;时,

  1.                    容器无需固定的width/height值,内部元素亦可拉伸;
  2.                    容器拉伸,内部元素支持百分比width/height值;

                    

  • left/right拉伸和width同时存在

对于position:absolute/fixed的元素,同时设置left、right和width,即可由margin:auto水平居中;

同理,top、bottom、height即可设置垂直居中。

【实践】absolute位置跟随实现下拉框定位

/*在HTML中将ul放在input前面,再利用absolute位置跟随特性,宽和高脱离了文档流不占空间特性,再配合margin来实现。*/
<-----------HTML代码------------->
            <div class="course-sidebar-search">
                <ul id="result" class="course-sidebar-result">
                                <li><a href="http://www.imooc.com/view/121">分享:CSS深入理解之float浮动</a></li>
                                <li><a href="http://www.imooc.com/view/118">案例:CSS圆角进化论</a></li>
                                <li><a href="http://www.imooc.com/view/93">案例:CSS Sprite雪碧图应用</a></li>
                                <li><a href="http://www.imooc.com/view/77">案例:CSS3 3D 特效</a></li>
                                <li><a href="http://www.imooc.com/view/57">案例:如何用CSS进行网页布局</a></li>
                </ul>
                <input class="course-search-input" placeholder="课程搜索">
                <a href="javascript:" class="course-search-btn">搜索</a>
            </div>

<-----------CSS代码------------->
        .course-sidebar-result 
{ display: none; position: absolute; width: 260px; margin: 39px 0 0 -1px; padding-left: 0; list-style-type: none; border: 1px solid #e6e8e9; background-color: #fff; box-shadow: 0px 1px 2px #d5d7d8; font-size: 12px; }
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>absolute实现下拉框定位</title>
    <style type="text/css">
                 body{margin: 0; font: 14px/1.4 "Microsoft YaHei"; background-color: #EDEFF0;}
                 .constr { width: 1200px; max-width: 80%; margin-left: auto; margin-right: auto;
                  padding-bottom: 300px; overflow: hidden; }

        .course-sidebar { width: 262px; float: left; }
        /* 设置下拉边框的样式值 */
        .course-sidebar > div { border: 1px solid #e6e8e9; box-shadow: 0px 1px 2px #d5d7d8; background-color: #fff; }
        .course-sidebar-type {height: 380px;}
        .course-sidebar-search { margin-top: 20px; overflow: hidden;}
        .course-search-input { width: 200px; line-height: 18px; padding: 10px; margin: 0; border: 0 none; font-size: 12px; font-family: inherit; float: left;}
        .course-sidebar-search.focus { border-color: #2ea7e0; }
        .course-search-input:focus { outline: 0 none; }
        .course-search-input: -ms-clear {display: none;}
        /* 搜索按钮的样式值 */
        .course-search-btn {width: 38px; height: 38px; float: right; background: url(img/search.png);  text-indent: -9em; overflow: hidden;}
        .focus .course-search-btn { background-position: 0 -38px; }

        /* 下拉框的样式值 */
        .course-sidebar-result { 
                                        display: none; 
                                        position: absolute;
                                         width: 260px; 
                                         margin: 39px 0 0 -1px; 
                                         padding-left: 0; 
                                         list-style-type: none; 
                                         border: 1px solid #e6e8e9; 
                                         background-color: #fff; 
                                         box-shadow: 0px 1px 2px #d5d7d8; 
                                         font-size: 12px; 
                                        }


                           .course-sidebar-result > li { line-height: 30px; padding-left: 12px; }
                          .course-sidebar-result > li:hover
                          {
                                       background-color: #f9f9f9;
                          }

                          .course-sidebar-result a 
                          {
                              display: block; 
                              color: #5e5e5e; 
                              text-decoration: none;
                          }
                          .course-sidebar-result a:hover{ color: #000; }
                         
    </style>
</head>
<body>
    <div class="constr">
              <div class="course-sidebar">
                  <div class="course-sidebar-type"></div>
            <div class="course-sidebar-search">
                <ul id="result" class="course-sidebar-result">
                                <li><a href="http://www.imooc.com/view/121">分享:CSS深入理解之float浮动</a></li>
                                <li><a href="http://www.imooc.com/view/118">案例:CSS圆角进化论</a></li>
                                <li><a href="http://www.imooc.com/view/93">案例:CSS Sprite雪碧图应用</a></li>
                                <li><a href="http://www.imooc.com/view/77">案例:CSS3 3D 特效</a></li>
                                <li><a href="http://www.imooc.com/view/57">案例:如何用CSS进行网页布局</a></li>
                </ul>
                <input class="course-search-input" placeholder="课程搜索">
                <a href="javascript:" class="course-search-btn">搜索</a>
            </div>
        </div>
              </div>
        
    </div>

    <script type="text/javascript">
(function() {
    var input = document.getElementsByTagName("input")[0],
        result = document.getElementById("result");
        
    if (input && result) {
        input.onfocus = function() {
            this.parentNode.className = "course-sidebar-search focus";
            if (this.value != " ") {
                // show datalist
                result.style.display = "block";
            }
        };
        input.onblur = function() {
            if (this.value == " ") {
                this.parentNode.className = "course-sidebar-search";
            }
            // hide datalist
            result.style.display = "none";
        };
                                            }
        })();
    </script>
</body>
</html>
源码

 

【绝对定位最佳实践】 实现图片居中以及边缘对齐定位

/* 技巧:

      要实现图片居中效果,可以在要absolute化的图片前面输入一个空格&nbsp (absolute具有位置跟随特性),
      最近父元素设置text-align:center;

      用margin-left:-(自身宽度)/2,调整。

*/
<!---------------------------HTML代码----------------------------> <div class="course-loading-x"> &nbsp;<img src="img/5453077400015bba00010001.gif" class="course-loading" alt="加载中..."> </div> <div class="course-fixed-x"> &nbsp;<div class="course-fixed"> <a href="#" class="goto_top_diaocha"></a> <a href="#" class="goto_top_app"></a> <a href="#" class="goto_top_feed"></a> </div> </div> <!---------------------------CSS代码----------------------------> .course-loading-x { height: 0; margin-top: 20px; text-align: center; /*//该样式对应的是&nbsp;*/ letter-spacing: -.25em; overflow: hidden; } /* //绝对定位的居中是相对于父元素*/ .course-loading { position: absolute; margin-left: -26px; } .course-fixed-x { height: 0; text-align: right; overflow: hidden; } .course-fixed { display: inline; /*//此元素会被显示为内联元素,元素前后没有换行符。*/ position:fixed; bottom: 100px;/* //(为了和body底部保持固定距离)*/ margin-left: 20px; }
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>边缘跟随的绝对定位</title>
    <style type="text/css">
        body { margin: 0; font: 14px/1.4 "Microsoft YaHei"; background-color: #EDEFF0; }
                          .constr { width: 1200px; max-width: 80%; margin-left: auto; margin-right: auto; }
                          .course-content { 
                              float: right; 
                              position: relative; 
                              width: 920px; 
                              min-height: 1200px; 
                              background: #fff;
                          }
                          .course-list-x {
                              padding: 20px 10px; 
                              overflow: hidden;
                          }
                          .course-list {
                              float: left;
                              width: 280px;
                              height: 240px;
                              margin: 5px 10px 15px; 
                              border-radius: 0 0 1px 1px;
                              background-color: #F7FAF9;
                              background-color: rgba(255,255,255,1);
                              box-shadow: 0 1px 2px #c5c5c5;
                              text-decoration: none;
                          }

                          .goto_top_diaocha, .goto_top_app, .goto_top_feed {
                                      display: block;
                                      width: 48px;
                                      height: 48px;
                                      margin-top: 10px;
                                      background: url(img/5453076e0001869c01920098.png);
                                      no-repeat;
                          }

                          .goto_top_diaocha { background-position: -48px 0; }
                          .goto_top_diaocha:hover { background-position: -48px -50px; }
                          .goto_top_app { background-position: -96px 0;}
                          .goto_top_app:hover { background-position: -96px -50px; }
                          .goto_top_feed { background-position: -144px 0; }
                          .goto_top_feed:hover { background-position: -144px -50px; }
                          
                          .course-loading-x { 
                              height: 0; 
                              margin-top: 20px; 
                              text-align: center;  /*//该样式对应的是&nbsp;*/
                              letter-spacing: -.25em;
                              overflow: hidden;
                          }
                         /* //绝对定位的居中是相对于父元素*/
                          .course-loading {
                              position: absolute;  
                              margin-left: -26px;
                          }

                          .course-fixed-x {
                              height: 0;
                              text-align: right;
                              overflow: hidden;
                          }
                          .course-fixed {
                              display: inline; /*//此元素会被显示为内联元素,元素前后没有换行符。*/
                              position:fixed; bottom: 100px;/* //(为了和body底部保持固定距离)*/
                              margin-left: 20px;
                          }




    </style>
</head>
<body>
<!--     绝对定位的特性,不设left和top值的话,他的位置是相对于他本来所应该处于文档流的位置,只是绝对定位后,他会飘起来,所以他具有跟随性,不与相对定位一起使用的话会产生更多更好的效果。
在绝对定位的元素之前是什么状态就是什么状态,比如说之前是inline,绝对定位之后还是inline水平,
唯独IE7不同,IE7会将所有绝对定位的元素设为display:inlien-block,解决办法是在绝对定位元素加一个无意义的父DIV标签, 
DIV标签要设置为:display:block;

技巧一,图片居中,可以在绝对定位的图片的前面输入一个空格,然后父div设定text-align:center,这样就将空格移动居中的地方去了,而由于绝对定位的跟随性,他也跟随在空格后面一起居中,在加上maigin-left:负的自身宽度/2,就稳稳当当居中了,居左居右都是同样的道理。 -->

         <div class="constr">
             <div class="course-content">
                 <div class="course-list-x">
                     <div class="course-list"></div>
                     <div class="course-list"></div>
                     <div class="course-list"></div>
                     <div class="course-list"></div>
                     <div class="course-list"></div>
                     <div class="course-list"></div>
                 </div>
                 <div class="course-loading-x">
                     &nbsp;<img src="img/5453077400015bba00010001.gif" class="course-loading" alt="加载中...">
                 </div>
                 <div class="course-fixed-x">
                     &nbsp;<div class="course-fixed">
                         <a href="#" class="goto_top_diaocha"></a>
                         <a href="#" class="goto_top_app"></a>
                         <a href="#" class="goto_top_feed"></a>
                     </div>
                 </div>
             </div>
         </div>
</body>
</html>
源码

 


Relative相对定位部分


 

relative对absolute的限制:

1、限制left/top/right/bottom定位

2、限制z-index层级;

3、限制在overflow下 

  • relative的z-index:auto;时候,不会限制内部absolute元素层叠

而relative对fixed的限制:只 限制z-index层级;

relative的最小化原则

/*单独定义一个div包裹要绝对定位的元素*/

<
div style="position:relative;"> <img src="abc.jpg" style="position:absolute;top:0;right:0;"> </div> <div> <div></div> <div></div> </div>