英文:
Navbar width greater than screen size even though width: 100%
问题
我正在以移动优先的方式构建网站,但我不明白为什么导航栏的宽度超出屏幕宽度。我在 414 x 896 屏幕上查看它。我将宽度设置为 100%,边距和内边距设置为 0,但仍然溢出。我还尝试了一个 div 元素,结果还是一样。我正在使用 Google DevTools 查看屏幕,也许是他们这边出了错误?
英文:
I am building a website mobile-first and I am lost at why the width of the navbar is going outside of the screen width. I am viewing it on a 414 x 896 screen. I set width: 100%, margin and padding to 0, yet it still overflows. I also tried a div element and the same thing happens. I am using Google DevTools to view the screen, maybe it's an error on their side?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html {
font-size: 16px;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
width: 100%;
}
<!-- language: lang-html -->
<nav>
<a>Log in</a>
</nav>
<!-- end snippet -->
I tried individually assigning padding and margin to the navbar and messing around with the height property
答案1
得分: 1
以下是已翻译的内容:
使用 calc()
:
html {
font-size: 16px;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
width: calc(100% - 2px);
}
使用 box-sizing
:
html {
font-size: 16px;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
width: 100%;
box-sizing: border-box;
}
英文:
The width of the nav is being calculated by adding the 100% plus the 1px borders. Either use calc()
to account for that, or change the box-sizing
:
Using calc()
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html {
font-size: 16px;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
width: calc(100% - 2px);
}
<!-- language: lang-html -->
<nav>
<a>Log in</a>
</nav>
<!-- end snippet -->
Using box-sizing
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html {
font-size: 16px;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
width: 100%;
box-sizing: border-box;
}
<!-- language: lang-html -->
<nav>
<a>Log in</a>
</nav>
<!-- end snippet -->
答案2
得分: 0
你将导航栏设为100%,然后添加了1像素的边框,使总体尺寸变大。
html {
font-size: 16px;
width:100%;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
}
<nav>
<a>Log in</a>
</nav>
英文:
You're setting the nav to 100%, and then adding a border of 1px to it which makes the total larger.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
html {
font-size: 16px;
width:100%;
}
* {
font-family: Verdana;
padding: 0;
margin: 0;
}
nav {
height: 50px;
border: 1px solid red;
}
<!-- language: lang-html -->
<nav>
<a>Log in</a>
</nav>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论