我有一个简单的页面,其中所有内容( <h1>
、 <h2>
、 <p>
等)都包含在 <div>
中, 以便具有相同的宽度。
我喜欢正文的外观并希望保持这种方式,但我想在标题中添加背景图像。它应该从页面的最顶部(在我的例子中是窗口)开始,到标题本身最后一行的基线结束,同时宽度也从窗口的左侧延伸到右侧。在下图中,我说明了所需的布局。在它下面,我绘制了我尝试过的 html 层次结构。
事实上,我已经尝试过创建 <h1>
的子项与
width: 100vw;
position: relative;
left: 50%;
transform: translate(-50%);
但是:
- 因为页面有
z-index: -1;
, 对于一些奇怪的错误我无法点击相对定位的链接 - 我不想使用
vw
因为浏览器支持而联合起来。 - 我仍然无法将背景扩展到顶部。
<h1>
的字体大小如您所见,它的边距以像素为单位定义,但页面仍然动态运行,因为当我调整窗口大小时,<h1>
的行数增加。
HTML
<div class="page">
<h1>Heading</h1>
<h2>Section 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
CSS
body {
height: 100%;
width: 100%;
margin:0px;
}
.page {
font-size: 20px;
width: 90%;
max-width: 70ch;
padding: 50px 5%;
margin: auto;
z-index: -1;
}
h1 {
font-size: 30px;
margin-top: 0;
margin-bottom: 10px;
}
h2 {
font-size: 22px;
margin-bottom: 26px;
}
p {margin-bottom: 24px;}
最佳答案
两个建议:
将 h1 和 body 的其余部分分开在两个不同的 div 中。将背景应用于第一个 div。
<div class="background-here">
<div class="page">
<h1>Heading</h1>
</div>
</div>
<div class="page">
<h2>Section 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
或者您可以将背景应用到正文并使用 background-repeat: repeat-x
或 bakcground-size: cover
。但这取决于图像的设计方式。
关于html - 使用 CSS 延伸到页面边缘和顶部的标题背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920524/