我想创建一个导航,左边为图像,右边为导航栏。导航的位置是固定的。 问题在于导航现在比其周围的主体更宽。
在固定导航位置的情况下,如何使导航与主体一样宽?
body {
margin: 20px 20px 0; }
body nav {
top: 0;
background-color: #fff;
padding: 10px 10px 0 0;
display: flex;
justify-content: space-between;
width: 100%;
position: fixed;
z-index: 99;
height: 80px; }
body nav .nav__logo {
width: 180px;
padding: 10px 0; }
body nav .nav__logo img {
width: 100%; }
body nav .nav__bar {
display: flex;
padding-right: 30px;
padding-left: 0;
justify-content: flex-end;
align-items: center;
flex: 1; }
body nav .nav__bar li {
margin: 0 20px; }
body nav .nav__bar .bar__level1 {
display: inline-flex; }
/*# sourceMappingURL=style.css.map */
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<title>Nav bar problem</title>
<link href="style.css" rel="stylesheet"/>
</head>
<body>
<nav>
<div class="nav__logo">
<a href="/" title="Start">
<img src="">
</a>
</div>
<div class="nav__bar">
<ul class="bar__level1">
<li><p>Start</p></li>
<li><p>Item1</p></li>
<li><p>Item2</p></li>
<li><p>Item3</p></li>
<li><p>Item4</p></li>
</ul>
</div>
</nav>
<main>
</main>
</body>
答案 0 :(得分:2)
您的资产净值大于body标签,因为您将body的边距设置为20px。
如果将左右位置属性设置为20px(与body的边距相同),则导航栏将与其父项(body标签)一样宽。
https://jsfiddle.net/dbku29oc/
body {
margin: 20px 20px 0; }
body nav {
top: 0;
left: 20px;
right: 20px;
background-color: #fff;
padding: 10px 10px 0 0;
display: flex;
justify-content: space-between;
/*width: 100%;*/
position: fixed;
z-index: 99;
height: 80px; }
body nav .nav__logo {
width: 180px;
padding: 10px 0; }
body nav .nav__logo img {
width: 100%; }
body nav .nav__bar {
display: flex;
padding-right: 30px;
padding-left: 0;
justify-content: flex-end;
align-items: center;
flex: 1; }
body nav .nav__bar li {
margin: 0 20px; }
body nav .nav__bar .bar__level1 {
display: inline-flex; }
/*# sourceMappingURL=style.css.map */
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<title>Nav bar problem</title>
<link href="style.css" rel="stylesheet"/>
</head>
<body>
<nav>
<div class="nav__logo">
<a href="/" title="Start">
<img src="">
</a>
</div>
<div class="nav__bar">
<ul class="bar__level1">
<li><p>Start</p></li>
<li><p>Item1</p></li>
<li><p>Item2</p></li>
<li><p>Item3</p></li>
<li><p>Item4</p></li>
</ul>
</div>
</nav>
<main>
</main>
</body>