我制作了一个菜单并使用 width: 100%
来确保它出现在整个页面上,但是左右两边都有空白(看起来更像 width:95 %
?) 然后我尝试使用 position:absolute top:0 left:0
解决了问题并使菜单看起来像宽度 100%,
不幸的是,此操作导致我的 h2
header 元素消失,我现在找不到正确放置它的方法?
JSBin code of my html and css code
#mainMenu {
font-family:Arial, Times, sans-serif;
list-style-type:none;
padding:0;
}
#mainMenu a {
text-decoration:none;
margin:5px;
padding:2px;
color:SeaGreen;
font-weight:bold;
}
#mainMenu a:hover {
color:Teal;
}
#menu {
text-align:center;
width:100%;
height:50px;
background-color:paleGoldenRod;
position:absolute;
left:0;
top:0;
}
li {
display:inline;
}
footer {
background-color:SlateGray;
height:150px;
width:100%;
position:absolute;
bottom:0;
left:0;
}
<!DOCTYPE html>
<html>
<head>
<title>Miko</title>
<link href="#" rel="stylesheet" type="text/css">
</head>
<body>
<div id="menu">
<ul id="mainMenu">
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">CONTACT ME</a></li>
</ul>
</div>
<h2>About The Page</h2>
<p>To Be Added</p>
<footer>
<p>Web Design</p>
</footer>
</body>
</html>
position:absolute
为什么让我的h2
消失了?
最佳答案
通常要避免默认边距,您可以将 margin: 0;
添加到 html
和 body
。
要将绝对定位的菜单放在 后面 h2
元素,您可以应用 z-index: -1
,它将它移到它的后面父元素。
在下面的代码片段中,我还将文本居中更改为右对齐,并在 ul
上添加了 padding-right。您可以使用这些值来满足您的需求。
html, body {
margin: 0;
}
#mainMenu {
font-family:Arial, Times, sans-serif;
list-style-type:none;
padding-right: 30px;
}
#mainMenu a {
text-decoration:none;
margin:5px;
padding:2px;
color:SeaGreen;
font-weight:bold;
}
#mainMenu a:hover {
color:Teal;
}
#menu {
text-align:right;
width:100%;
height:50px;
background-color:paleGoldenRod;
position: absolute;
z-index: -1;
}
li {
display:inline;
}
footer {
background-color:SlateGray;
height:150px;
width:100%;
position:absolute;
bottom:0;
left:0;
}
<!DOCTYPE html>
<html>
<head>
<title>Miko</title>
<link href="#" rel="stylesheet" type="text/css">
</head>
<body>
<div id="menu">
<ul id="mainMenu">
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">CONTACT ME</a></li>
</ul>
</div>
<h2>About The Page</h2>
<p>To Be Added</p>
<footer>
<p>Web Design</p>
</footer>
</body>
</html>
关于html - 位置 :absolute css menu hides my h2 element, 如何克服这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43453214/