css - 为什么 CSS 'padding' 在我的元素中创建边距?

标签 css margin padding

我有一个宽度为 100% 的“ul”,但是当我在其中放入“padding”时,右边距出现了。为什么会这样?代码如下。

nav ul {
  list-style: none;
  text-align: center;
  background-color: rgb(90, 32, 102);
  line-height: 3.125em;
  position: relative;
  right: 38px;
  width: 100%;
  padding: 1em 0;
}
<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Products</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

最佳答案

使用 position: relativeright: 38px 在这里不是惯用的。它是说将 ul 元素的右边缘移动到它们通常所在位置的左侧 38px,从而创建右边距。最好的第一步可能是删除这两个属性。

您似乎想要一个没有元素符号的居中列表,这就是结果。 ul 缩进设置了 padding,左边已经设置为 0。

起初,我误读了这个问题,认为 li 元素太宽而破坏了样式。所提供的建议已被接受,因此我认为即使不是答案也会有所帮助。

默认情况下,填充超出元素的宽度,因此您的 ul block 实际上是 100% + 1em

使用 css 的 box-sizing 属性来应用 box-sizing: border-box; 会产生预期的行为。

https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

border-box The width and height properties include the content, padding, and border, but do not include the margin. Note that padding and border will be inside of the box. For example, .box {width: 350px; border: 10px solid black;} renders a box that is 350px wide. The content box can't be negative and is floored to 0, making it impossible to use border-box to make the element disappear.

关于css - 为什么 CSS 'padding' 在我的元素中创建边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737698/

相关文章:

javascript - JQuery 删除样式表和 JS

android - 底部导航 Activity 在 fragment 顶部显示意外的边距

css - <li> 元素有多余的垂直间距

xaml - 如何调整XAML标签中的填充

html - Google Chrome Bug,CSS Padding 样式应用于空单元格

html - 如何为液体布局完美对齐 div?

css - <span> 里面的 <a> 链接问题

css - html 中产品的图库 View

css - Flex 创造了不会消失的利润

c - 如何告诉 gcc 禁用结构内的填充?