⭐⭐⭐🍔🍔🍔🏳️🌈🏳️🌈🏳️🌈
目录
⭐先说大招
案例1
平时学的时候没有在意这一点,感觉很简单,但是真正实践的时候就傻眼了🤐
先来一个题目
盒子尺寸300*300,背景天蓝色,边框10px实线黄绿色,上下左右20px的内边距,水平居中
错误代码
错误代码
错误代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 300px; height: 300px; background-color: skyblue; border: 10px solid greenyellow; padding: 20px; } </style> </head> <body> <div></div> </body> </html>
结果
右击检查,发现盒子大小已经超出300px了
原因:
⭐border会撑大盒子
⭐padding会撑大盒子
解决方法
那么为了实现需求,可以改变盒子的实际宽度
(实际大小=左border+左padding+内容宽度+右padding+右border)
那么变成width: 240px即可
🚥🚥🚥🚥🚥🚥
案例2
下面我将用两种方法来实现下图的布局
法一:
使用浮动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box{ margin: 0 auto; position: relative; width: 800px; height: 794px; border: 1px solid black; } .header{ margin: 0 auto; height: 198px; width: 790px; margin-top: 4px; margin-bottom: 4px; border: 1px solid black; } .leftside { float: left; height: 498px; width: 292px; margin-left: 4px; margin-right: 4px; border: 1px solid black; } .rightside{ float: right;/*一定得是右浮动,不是左浮动*/ margin-right: 4px; height: 498px; width: 492px; border: 1px solid black; } .footer{ position: absolute;/*这样子把footer盒子固定在大盒子底部*/ margin-top: 4px; margin: 0 auto; margin-left: 4px; bottom: 4px; height: 76px; width: 790px; border: 1px solid black; } </style> </head> <body> <div class="box"> <div class="header">header</div> <div class="leftside">leftside</div> <div class="rightside">rightside</div> <div class="footer">footer</div> </div> </body> </html>
法二:
使用位置定位
父相子绝(父亲属性是:relative,儿子属性是:absolate)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box { margin: 0 auto; position: relative;/*父相子绝*/ width: 800px; height:794px ; border: 1px solid; } .header { margin: 4px; border: 1px solid; width: 790px; height: 198px; } .leftside { position: absolute;/*父相子绝*/ left: 4px; /*离父盒子左边距的距离*/ bottom: 86px; /*离父盒子下边距的距离*/ border: 1px solid; width: 292px; height: 498px; } .rightside { position: absolute;/*父相子绝*/ left: 302px; right: 4px; bottom: 86px; width: 492px; height: 498px; border: 1px solid; } .footer { position: absolute;/*父相子绝*/ margin-left:4px ; margin-right: 4px; bottom: 4px; width: 790px; height: 76px; border: 1px solid; } </style> </head> <body> <div class="box"> <div class="header">header</div> <div class="leftside">leftside</div> <div class="rightside">rightside</div> <div class="footer">footer</div> </div> </body> </html>
Code over!