如何防止我的div溢出其父容器?

时间:2016-04-26 21:38:01

标签: html css

以下是我从codepen中获取的代码:http://codepen.io/rags4developer/pen/ONoBpm

请帮我解决这些问题。

  1. 如何阻止主div和&从容器div溢出的页脚?溢出:隐藏容器并不总是有效!
  2. 如何在不将高度设置为固定百分比的情况下使容器div高度等于页面高度?
  3. HTML:

    <body>
     <div id="container">
       <div id="nav">nav links 1,2,3 etc</div>
       <div id="main">
         <!--no text here-->
         <div id="left">left panel</div>
         <div id="right">right panel</div>
       </div>
       <div id="footer">footer</div>
     </div> 
    </body>
    

    CSS:

    * {box-sizing: border-box;}
    html {height: 100%;}
    body {height: 100%;}
    #container {
      border: 8px solid yellow;
      height: 100%;
      width: 80%;
      margin: 0 auto;
    }
    
    #nav {
      border: 4px solid red;
      height: 15%;
    }
    
    #main {
      border: 4px solid black;
      height: 100%;
      background: gray;
    }
    
    #left {
      border-top: 4px solid green;
      border-left: 4px solid green;
      border-bottom: 4px solid green;
      float: left;
      width: 15%;
      height:100%;
      /*I will make this gradient later*/
      background: #9e9999;
    }
    
    #right {
      border: 4px solid blue;
      float: right;
      width: 85%;
      height: 100%;
      border-radius: 20px 0 0 0;
      background: white;
    }
    
    #footer {
      border: 4px solid pink;
      clear: both;
    }
    

3 个答案:

答案 0 :(得分:1)

我不完全确定我是否理解正确,但你的高度(即#container div内的高度)加起来为15%+ 100%+页脚高度=至少115% #container高度加上页脚高度,导致&#34;溢出&#34;。

我将#content高度更改为80%并将height: 5%;添加到您的codepen的这个分支中的页脚:http://codepen.io/anon/pen/EKeOdm

现在一切都在#container之内。这是你想要的吗?

答案 1 :(得分:0)

clearfix 解决方案仍适用于浮动元素IMO。尝试删除高度样式并添加:

#main:before,
#main:after {
  display: table;
  content: "";
}

#main:after {
  clear: both;
}

进一步:http://nicolasgallagher.com/micro-clearfix-hack/

答案 2 :(得分:0)

使用显示表应该解决这个问题。

#container {
    border: 8px solid yellow;
    height: 100%;
    width: 80%;
    margin: 0 auto;
    **display: table;**
}

#content {
    border: 4px solid black;
    background: gray;
    height: 100%;/*Not sure 100% of what ? Parent ???*/
    **display: table-row;**
}
相关问题