html - 为什么向 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
页眉元素的边距,而不是移动整个图像?
解决方案
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 答案。
推荐阅读
- python - 使用python中的子进程模块实时输出终端命令
- erlang - 使用 httpc lib 将大型 http 响应流式传输到 Erlang 中的磁盘
- javascript - 按 Client_id 下载 Google Analytics 数据
- sql - 使用正则表达式从 Oracle 查询字符串中选择一个词
- azure - 在 sap hana azure vm 备份中找不到 SYSTEM_KEY_NAME
- image-processing - val_loss 非常高(超过 100)
- sql - SQL 到 HiveQL 的转换
- windows - 如何创建更改我的 MAC 地址的批处理文件?
- javascript - Cypress 和不稳定的 DOM
- javascript - 如何使用 C# Selenium 更改 HTML 范围输入值