为什么这些元素不留在它们的DIV容器中?

Why are these elements not staying within their DIV container?

本文关键字:DIV 元素 为什么      更新时间:2023-09-26

我是CSS的新手,我不清楚为什么标题和菜单链接留在容器内,而不是其他元素。我可以通过包括其他元素的边距来解决这个问题,但我想了解为什么会发生这种情况。

是否有一种方法可以在不指定每个元素的外边距的情况下将元素保留在容器内?例如,请参阅JS代码和下面的代码。我希望将#main内容保留在#container中。

JSFiddle链接:http://jsfiddle.net/6qt8ry1L/

body {
  background-color: #F7F7F0;
}
#container {
  width: 1000px;
  position: relative;
  margin: 0 auto;
  text-align: center;
  background-color: #8e8e20;
}
header {
  background-image: url("header.jpg");
  background-repeat: no-repeat;
  height: 224;
}
h1 {
  color: #ffffff;
  padding: 10px;
  text-align: left;
}
#nav ul {
  list-style: none;
  background-color: black;
  height: 40px;
  margin-top: 0;
  color: white;
}
#nav li {
  display: inline-block;
  padding-top: 10px;
  padding-left: 50px;
  padding-right: 50px;
  padding-bottom: 10px;
}
#MainContent {
  margin-top: 10px;
  padding-top: 20px;
  border-top: 1px solid #545454;
  background-color: #b6c5a3;
  height: 200;
  color: #492b40;
  font: 11px/12px Verdana, Arial, Helvetica, sans-serif;
}
#col1 {
  width: 20%;
  height: 30%;
  margin-top: 15px;
  float: left;
  background-color: lightgray;
}
#col2 {
  float: left;
  margin-left: 1%;
  margin-top: 15px;
  height: 30%;
  width: 20%;
  background-color: lightgray;
}
#col3 {
  float: left;
  margin-top: 15px;
  width: 20%;
  height: 30%;
  margin-left: 1%;
  background-color: lightgray;
}
#Content:after {
  content: '';
  display: block;
  clear: both;
}
#footer {
  float: left;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #545454;
  background-color: #b6c5a3;
  height: 60;
  width: 950px;
  color: #492b40;
  font: 11px/12px Verdana, Arial, Helvetica, sans-serif;
}
<html>
<head>
  <link rel="stylesheet" href="Style.css">
</head>
<body>
  <div id="container">
    <header>
      <div id="heading">
        <h1> Hello there !!! </h1>
      </div>
    </header>
    <div id="nav">
      <ul>
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
        <li>Links</li>
      </ul>
    </div>
  </div>
  <div id="MainContent">
    Main Content
  </div>
  <div id="Content">
    <div id="col1">
      Col1
    </div>
    <div id="col2">
      col2
    </div>
    <div id="col3">
      col 3
    </div>
  </div>
  <div id="footer">
    <p>Copyright 2004 xyz Association</p>
    <p>All rights reserved etc etc..</p>
  </div>
  </div>
  <!--end container-->
</body>
</html>

容器在关闭div#nav后关闭。把结束的div放在最后,你的问题就解决了。

我注意到你有更多的结束标签比你有开始div。作为一个习惯,当你创建<DIV>时,一定要立即插入</DIV>。跟踪开市和闭市div。我猜这个不匹配关闭div可能是您的问题的原因。