外边距margin
外边距是盒子与盒子之间的距离,设置方法与内边距padding非常相似。
margin他是一个复合属性,有四个方向↓
margin-top: 10px;
margin-right: 10px;
margin-bottom: 10px;
margin-left: 10px;
练习↓
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } div{ width: 100px; height: 100px; background-color: red; border: 1px solid blue; } </style> </head> <body> <div></div> <div></div> </body> </html>
不给div设置margin属性时,效果图↓
给div设置margin属性后,代码↓
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } div{ width: 100px; height: 100px; background-color: red; border: 1px solid blue; margin-top: 10px; } </style> </head> <body> <div></div> <div></div> </body> </html>
显然我给div设置了一个上边距的属性,效果图↓
复合属性写法↓
/*上 下 左 右*/
margin: 10px 20px 30px 40px;
/*上 左右 下*/
margin: 10px 20px 30px;
/*上下 左右*/
margin: 10px 20px;
让盒子水平居中
属性值:auto
代码↓
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } div{ width: 100px; height: 100px; background-color: red; border: 1px solid blue; margin: 200px auto; } </style> </head> <body> <div></div> </body> </html>
效果图↓