html - CSS 为什么 div 会重叠?
问题描述
我正在尝试仅使用 css 创建一个响应式网站。.我有一个包含所有代码的容器。在里面,我有导航 div 和中间 div。容器是相对定位的,而导航和中间是绝对定位的。另外,有点奇怪的问题,但在 Internet Explorer 中(不要判断)导航部门的下拉菜单是水平打开而不是垂直打开。我似乎找不到这样做的原因。
这是代码(我的原始 css 代码由 css 的 Chris Happy 改进-为什么我的导航 div 和中间 div 重叠?)
div#Container
{
position: relative;
}
.nav
{
width: 100%;
position: absolute;
background-color: white; /*Code to add a white background to list*/
padding: 15px;
}
.nav a
{
color: #ffffff;
text-decoration: none;
background-color: #000000;
}
.nav ul
{
display:block;
}
.nav ul a
{
display: block;
float:left;
width: 150px;
padding: 10px 20px;
border: 1px solid #ffffff;
text-align: center;
font-size: 1.3em;
}
.nav ul a:hover
{
background: red;
}
.nav ul li
{
display: inline-block;
vertical-align: top;
}
.nav ul ul li { display: block; }
.nav ul li:hover > ul
{
display:block;
}
.nav ul li ul
{
margin:0;
padding: 0;
display: none;
background-color: #000000;
top: 45px;
}
div#middle
{
position: absolute;
}
<div id="Container">
<div class="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Cars</a></li>
<li><a href="#">Parts & Tools</a>
<ul>
<li><a href="#">Parts</a></li>
<li><a href="#">Tools</a></li>
</ul>
</li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
<div class="middle">
<p>text</p>
</div>
</div>
解决方案
我没有看到中间 div 的 HTML,但绝对位置意味着相对于 div #container 的“框架”的固定位置。所以 div nav 和 div middle 重叠导致它们相互忽略并且都相对于 div #container 定位。你可以给 div 固定宽度和高度以及固定边距,这样它们就不会发生冲突。例子:
.nav
{
position: absolute;
margin-top: 0;
margin-left: 0;
width: 300px;
}
.middle
{
position: absolute;
margin-top: 0;
margin-left: 300px;
}
另一个例子
<html>
<head>
</head>
<body>
<div style="position: relative;border: solid;margin: 40px;height: 300px;">
<div style="position: absolute; margin: 50px 100px; border: solid; width: 100px;height: 100px;">
</div>
<div style="position: absolute; margin: 40px 90px; border: solid; width: 100px;height: 100px;">
</div>
</div>
</body>
</html>
推荐阅读
- c# - C# 和 PDFsharp 按名称合并目录中的 2 个 pdf 文件。有许多
- java - 一对反斜杠被一个斜杠替换
- ballerina - Ballerina 0.980.0 - 如何为 jdbc:Client 设置超时?
- linq - 如何将 SQL 转换为 LINQ c#(左外连接、空分配到字符串数据类型和 NVL() 转换)
- linux - 在 Docker 容器中运行 Cron 作业
- python - 如果子查询中的所有对象都具有特定值,则在 Django 2 中过滤对象
- hibernate - Spring Data JPA - 无法重用参数
- jquery - 使用 Jquery 进行 CSS 转换
- excel - 多个范围的 VBA 行
- java - 如何获取线性布局的子节点的位置?