1. 程式人生 > >盒子模型 margin和padding和盒子大小的影響

盒子模型 margin和padding和盒子大小的影響

margin 是盒子的外邊距

padding是盒子的內邊距

border是盒子的外邊框

它們對盒子的寬度是有影響的,下邊舉一個例子:

首先是html:

<html>
<head></head>
<style type="text/css">
 .div{
width:400px;
height:400px;
background-color:red;
}
 .div1{
float:left;
width:200px;
height:200px;
background-color:green;
}
 .div2{
float:left;
width:200px;
height:200px;
background-color:blue;
}
</style>
<body>
        <div class="div">
  		<div class="div1"></div>
		<div class="div2"></div>
	
	<div>
</body>


兩個盒子的寬度正好充滿父容器:

此時如果把div1 div2分別加上margin:10px 盒子寬度就會加上外邊距,寬度超過父容器:

同理,加上padding和border的話也同樣增加了盒子寬度,所以要使兩個盒子寬度不溢位,div的寬度需要減去所增加的屬性寬度:

<html>
<head></head>
<style type="text/css">
 .div{
width:400px;
height:400px;
background-color:red;
}
 .div1{
margin:10px;
float:left;
width:180px;
height:180px;
background-color:green; } .div2{ margin:10px; float:left; width:180px; height:180px; background-color:blue; } </style> <body> <div class="div"> <div class="div1"></div> <div class="div2"></div> <div> </body> </html>


相關推薦

no