CSS如何解決子項目越界

來源:互聯網
上載者:User

1.補充:CSS中盒子模型的計算方式

  .box {

box-sizing:  content-box / border-box;

  }

content-box:一個盒子的總寬=margin+border+padding+width,即width只是指盒子中內容的寬度

border-box: 一個盒子的總寬=margin+width,即width是內容、padding、border的寬度和

 

 

2.補充:如何解決子項目的margin-top/bottom的越界問題

  如下圖:父容器parent2中第一個子項目child2,若想通過設定margin-top屬性來實現在父容器中往下移動20px的效果是不可行的。

反而會讓父元素div跟著child2一起向下移動20px。如何解決這類問題呢。

 

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="2015/11/26cription" content="">  <style>* {box-sizing: border-box;}.parent1, .parent2 {width: 600px;height: 200px;}.parent1 {background: #aaf;}.parent2 {background: #afa;/*border-top: 1px solid #000;*//*margin-top: 0;*//*padding-top:0px;*//*overflow: hidden;*/}.child2 {width: 100px;height: 50px;background: #faf;margin-top: 20px;}  </style> </head> <body>    <div class="parent1">  </div>  <div class="parent2"><div class="child2">child2為父容器div的第一個子項目</div>  </div> </body></html>


解決方案:

(1)給父元素加border——有副作用: 一般父元素Div用來做布局使用,添加border會使用內容的height和width變大

(2)給父元素加padding-top:1px——有副作用

(3)給父元素加overflow:hidden——有副作用:一旦子項目內容溢出,將會無法顯示溢出的內容

(4)為父元素新增內容產生:該方法無任何副作用

.parent:before {

content:  ‘  ’;

display: table;

}


<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="2015/11/26cription" content="">  <style>* {box-sizing: border-box;}.parent1, .parent2 {width: 600px;height: 200px;}.parent1 {background: #aaf;}.parent2 {background: #afa;/*border-top: 1px solid #000;*//*margin-top: 0;*//*padding-top:0px;*//*overflow: hidden;*/}.parent2:before {content: ' ';display: table;}.child2 {width: 100px;height: 50px;background: #faf;margin-top: 20px;}  </style> </head> <body>    <div class="parent1">  </div>  <div class="parent2"><div class="child2">child2為父容器div的第一個子項目</div>  </div> </body></html>


 

3.補充:子項目全部浮動後父元素高度為0

 解決方案:

(1)給父元素加overflow:hidden——有副作用

(2)為父元素添加後置內容產生

.parent:after {

content: ‘  ’;

display: table;

clear: both;

}

 

 

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="2015/11/26cription" content="">  <style>* {box-sizing: border-box;}.parent1 {width: 600px;background: #aaf;/*overflow: hidden;*/}.parent1:after {content: ' ';display: table;clear: both;}.child1, .child2, .child3 {width: 150px;border: 1px solid #000;float: left;}  </style> </head> <body>    <div class="parent1"><div class="child1">1111</div><div class="child2">2222</div><div class="child3">3333</div><!--<div style="clear:both;"></div>-->  </div>    <hr> </body></html>


 

  

 

 

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.