CSS- margin-top 不工作

CSS- margin-top not working

#modal {
  background-color: #f0f0f0;
  //border: thin red solid;
  height: 500px;
}
#category_main {
  width: 75%;
  height: 200px;
  border: thin red solid;
  display: block;
  margin: 0 auto;
  margin-top: 5%;
}
<div id="modal">
  <div id="category_main"></div>
</div>

当我 运行 then 时,margin-top 不起作用。 div category_main 随 div 一起出现。我不想要那个白色的部分。而不是 ,只有红色边框框应该受到影响 margin-top

谢谢。

任何帮助将不胜感激。

overflow:hidden 添加到父级,以便父级获得您指定的实际高度..

这是代码段

#modal{
        background-color: #f0f0f0;
        /*border: thin red solid;*/
        height: 500px;
        overflow:hidden;
}

  #category_main{
                width: 75%;
                height:200px;
                border: thin red solid;
                margin: 0 auto;
                margin-top: 15%;
            }
<div id="modal">
    <div id="category_main"></div>
</div>

注意

In css 注释应该在 /*.......*/ 之间传递,而不是 //....

不应将 margin-top 应用于 #category_main,而应将 padding-top 应用于 #modal,因为前者留下了一个空白,而后者包含了相同的内容:

#modal{
    background-color: #f0f0f0;
    //border: thin red solid;
    height: 500px;
    padding-top: 5%;
}

观看演示 ​​here

我认为你理解错了。你想在外面 div 上填充。

 padding-top: 5%;

将此 css 用于 #modal

vertical-align:middle;

display: table-cell;

#modal {
  background-color: #f0f0f0;
  //border: thin red solid;
  height: 500px;
  width: 500px;
  vertical-align: middle;
  display: table-cell;
}
#category_main {
  width: 75%;
  height: 200px;
  border: thin red solid;
  display: block;
  margin: 0 auto;
  margin-top: 5%;
}
<div id="modal">
  <div id="category_main"></div>
</div>

Really if u dont want the white space as you desired, just add padding:5% to the main div..May b this will solve your problem

#modal {
  background-color: #f0f0f0;
  //border: thin red solid;
  height: 500px;
  padding: 5%;
}
#category_main {
  width: 75%;
  height: 200px;
  border: thin red solid;
  display: block;
  margin: 0 auto;
 
}
<div id="modal">
  <div id="category_main"></div>
</div>

#modal {
  background-color: #f0f0f0;
  //border: thin red solid;
  height: 500px;
  padding:5%;
}
#category_main {
  width: 75%;
  height: 200px;
  border: thin red solid;
  display: block;
  margin: 0 auto;

}
<div id="modal">
  <div id="category_main"></div>
</div>