首页 > 解决方案 > 为什么向 h1 元素添加边距会改变整个标题类?

问题描述

我正在尝试使用 HTML 和 CSS 将标题文本集中在标题背景图像上。

我在标题类中设置了背景图像:

.header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-6/htmlcss1-img_burgerphoto.jpeg");
  background-position: center;
  background-size: cover;
  height: 320px
}

然后在 a 中操作文本.header h1

.header h1 {
  background-color: #05A8AA;
  color: #FFF;
  font-family: 'Oswald', sans-serif;
  font-size: 40px;
  font-weight: 300;
  line-height: 40px;
  width: 68%;
  padding: 20px;
  margin: 0 auto;
}

如果我添加到第二个代码块 quality position: relative;,那么我可以操纵top来实现我的目标。

我的困惑是,当我调整 中的margin-top属性时.header h1,它会向下移动整个标题,包括背景图像,而不是在背景图像上向下移动h1文本。

我的问题是为什么?为什么调整h1页眉元素的边距,而不是移动整个图像?

标签: htmlcss

解决方案


h1将您的内部准确居中的最简单和最简单的方法是header添加样式。如果您修改任何其他变量,例如标题宽度、高度、标题文本长度、字体大小等,使用“魔术”值作为边距或位置偏移量的其他方法将很脆弱并且会中断。我建议使用以下方法:display: flex; justify-content: center; align-items: center;header

header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-6/htmlcss1-img_burgerphoto.jpeg");
  background-position: center;
  background-size: cover;
  height: 320px;
  display: flex;
  justify-content: center;
  align-items: center;
}
  
header h1 {
  background-color: #05A8AA;
  color: #FFF;
  font-family: 'Oswald', sans-serif;
  font-size: 40px;
  font-weight: 300;
  line-height: 40px;
  width: 60%;
  padding: 20px;
}
<header><h1>header text</h1></header>

更新:了解保证金崩溃

MDN 对此有很好的文档,但总结一下您的特定示例:当没有中间位置时,子项的垂直边距与其父项的垂直边距“折叠”,例如填充、边框、内联内容等。所以当你添加margin-top到你的h1嵌套中,header它的垂直边距“折叠”,header这就是为什么两个元素都向下移动的原因。这是一个例子:

header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-6/htmlcss1-img_burgerphoto.jpeg");
  background-position: center;
  background-size: cover;
  height: 320px;
}
  
header h1 {
  background-color: #05A8AA;
  color: #FFF;
  font-family: 'Oswald', sans-serif;
  font-size: 40px;
  font-weight: 300;
  line-height: 40px;
  width: 60%;
  padding: 20px;
  margin-top: 100px;
}
<header><h1>header text</h1></header>

如果您想防止边距崩溃,有很多解决方案,但在这种情况下,最简单的一种可能是添加overflow: auto类似header这样的解决方案:

header {
  background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/unit-6/htmlcss1-img_burgerphoto.jpeg");
  background-position: center;
  background-size: cover;
  height: 320px;
  overflow: auto;
}
  
header h1 {
  background-color: #05A8AA;
  color: #FFF;
  font-family: 'Oswald', sans-serif;
  font-size: 40px;
  font-weight: 300;
  line-height: 40px;
  width: 60%;
  padding: 20px;
  margin-top: 100px;
}
<header><h1>header text</h1></header>

如果您对禁用边距折叠的其他方法感兴趣,那么我建议您阅读此 StackOverflow 答案


推荐阅读