2016-07-23 60 views
0

我試圖讓幾個嵌入式色塊同心使用下面的代碼:如何用css製作同心色塊?

#div1, #div2, #div3, #div4, #div5 { 
 
    width: 300px; 
 
    height: 300px 
 
} 
 
#div1 { 
 
    background: yellow; 
 
} 
 
#div2 { 
 
    background: orange; 
 
    padding: 50px; 
 
} 
 
#div3 { 
 
    background: red; 
 
    padding: 100px; 
 
} 
 
#div4 { 
 
    background: purple; 
 
    padding: 150px; 
 
}
<div id="div4"> 
 
    <div id="div3"> 
 
    <div id="div2"> 
 
     <div id="div1"></div> 
 
    </div> 
 
    </div> 
 
</div>

然而,這是我所得到的: enter image description here

的DIV1和DIV2塊嵌入同心正如預期的那樣,但其他兩個外部塊似乎在填料上崩潰。代碼有什麼問題?

回答

2

您只需要設置最內層元素的widthheight。其餘的尺寸可以用padding來確定。將display: inline-block放在最外面的元素上以防止伸展,或將其width設置爲500px

#div1 { 
 
    width: 300px; 
 
    height: 300px; 
 
    background: yellow; 
 
} 
 
#div2 { 
 
    background: orange; 
 
    padding: 50px; 
 
} 
 
#div3 { 
 
    background: red; 
 
    padding: 50px; 
 
} 
 
#div4 { 
 
    background: purple; 
 
    padding: 50px; 
 
    display: inline-block; 
 
}
<div id="div4"> 
 
    <div id="div3"> 
 
    <div id="div2"> 
 
     <div id="div1"></div> 
 
    </div> 
 
    </div> 
 
</div>

0

這應該爲你工作。

<!DOCTYPE html> 
<html> 
<head> 
<title>Page Title</title> 
<style> 
#div1 { 
width: 300px; 
height: 300px; 
background: yellow; 
margin: auto; 
} 
#div2 { 
background: orange; 
padding: 50px; 
} 
#div3 { 
background: red; 
padding: 50px; 
} 
#div4 { 
background: purple; 
padding: 50px; 
} 
</style> 
</head> 
<body> 
</html>