2016-10-04 48 views
0

我正在练习这个简单的代码,当我试图把background放在我的P后面使用(div) element它没有显示为什么? 我想要的是div { background-color: purple; } 涵盖了我所有的'(p)部分'。HTML背景未显示

我的代码

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 

    <title>Boxes</title> 
<h1 align="center">My Boxes</h1> 


<style> 

div { 
    background-color: purple; 

} 


p { width: 50px; 
    height: 50px; 
    border: 2px solid black; 
    margin-bottom: 10px; 
    margin-right: 10px; 
    float:left; 
} 
h1 {margin-bottom: 80px; 
} 

* {box-sizing: border-box; 
margin: 0; 
padding: 0;} 

#box1 {background-color: yellow; 




} 
#box2 {background-color: red; 


} 
#box3 {background-color: blue; 
    clear:left; 

} 
#box4 {background-color: green;} 



</style> 
</head> 

<body> 
<div> 

<p id="box1"> </p> 
<p id="box2"> </p> 
<p id="box3"> </p> 
<p id="box4"> </p> 

</div> 


</body> 
</html> 
+0

这是因为您已经添加'浮动:left'你'p'这使得浮动元素里面的div,这就是为什么div有没有采取任何高度。您不需要添加此样式以使元素保持在左侧。 – Rohit416

回答

0

你可以使用overflow:auto更改DIV因为你已经使用浮到p应该清除浮于母公司的认识高度。

div { 
 
    background-color: purple; 
 
    overflow:auto; 
 

 
} 
 

 

 
p { width: 50px; 
 
    height: 50px; 
 
    border: 2px solid black; 
 
    margin-bottom: 10px; 
 
    margin-right: 10px; 
 
    float:left; 
 
} 
 
h1 {margin-bottom: 80px; 
 
} 
 

 
* {box-sizing: border-box; 
 
margin: 0; 
 
padding: 0;} 
 

 
#box1 {background-color: yellow; 
 

 

 

 

 
} 
 
#box2 {background-color: red; 
 

 

 
} 
 
#box3 {background-color: blue; 
 
    clear:left; 
 

 
} 
 
#box4 {background-color: green;}
<div> 
 

 
<p id="box1"> </p> 
 
<p id="box2"> </p> 
 
<p id="box3"> </p> 
 
<p id="box4"> </p> 
 

 
</div>

0

你标记使用<p>标签不<div>标签。

#box1 p {background-color: yellow; } 
#box2 p {background-color: red; } 
#box3 p {background-color: blue; clear:left;} 
#box4 p {background-color: green; } 

而且这属于内部<body>

<h1>My Boxes</h1> 
0

只是你把高度:100vh;宽度:100%;在你的CSS Div标签选择器类

div { 
 
    height:100vh; 
 
    width:100%; 
 
    background: purple; 
 
      
 
} 
 

 

 
p { width: 50px; 
 
    height: 50px; 
 
    border: 2px solid black; 
 
    margin-bottom: 10px; 
 
    margin-right: 10px; 
 
    float:left; 
 
} 
 
h1 {margin-bottom: 80px; 
 
} 
 

 
* {box-sizing: border-box; 
 
margin: 0; 
 
padding: 0;} 
 

 
#box1 {background-color: yellow; 
 

 

 

 

 
} 
 
#box2 {background-color: red; 
 

 

 
} 
 
#box3 {background-color: blue; 
 
    clear:left; 
 

 
} 
 
#box4 {background-color: green;}
<body> 
 
<div> 
 

 
<p id="box1"> </p> 
 
<p id="box2"> </p> 
 
<p id="box3"> </p> 
 
<p id="box4"> </p> 
 

 
</div>