day20—CSS中伪类:before与:after的应用:

转行学开发,代码100天——2018-04-05

 CSS中的两个伪类:before和:after适合应用与在元素的开始或者结尾处添加修饰性文字或外观,实现内容添加的同时并没有破坏HTML代码

语义。如之下的一个应用

  <div class="main">
      <div class="slider">this is a slider bar</div>
      <div class="content">this is the main content </div>
      <div class="clear">clear</div>
  </div>
<style type="text/css">
      .slider{
        float: left;
        width: 150px;
        border: 1px solid red;
      }
      .content{
          float: right;
          width: 450px;
          border: 1px solid red;
      }
      .clear{
          clear: both;
          border: 1px solid red;
      }
    </style>

 上例中为了清除浮动,添加了一个<div>盒子,并为此div添加了clear样式。这是一个常规的用法,但这种方式破坏了HTML代码的语义,并不是一个很好的方案,应该删除这个对于的<div>元素,并修改CSS样式如下:

 <div class="main clearfix">
  	<div class="slider">this is a slider bar</div>
  	<div class="content">this is the main content </div>
  	<!-- <div class="clear">clear</div> -->
  </div>

  

<style type="text/css">
      .slider{
        float: left;
        width: 150px;
        border: 1px solid red;
      }
      .content{
          float: right;
          width: 450px;
          border: 1px solid red;
      }
      .clearfix{
          *zoom:1;
      }
      .clearfix:before,
      .clearfix:after{
          content: "";
          display: table;
      }
      .clearfix:after{
          clear: both;
      }
    </style>

修改后的代码使用了:before和:after伪类,很好地解决了由于多余的元素而破坏HTML代码语义的问题。

原文地址:https://www.cnblogs.com/allencxw/p/8744609.html