html - 使用 CSS 延伸到页面边缘和顶部的标题背景图片

标签 html css

我有一个简单的页面,其中所有内容( <h1><h2><p> 等)都包含在 <div> 中, 以便具有相同的宽度。

我喜欢正文的外观并希望保持这种方式,但我想在标题中添加背景图像。它应该从页面的最顶部(在我的例子中是窗口)开始,到标题本身最后一行的基线结束,同时宽度也从窗口的左侧延伸到右侧。在下图中,我说明了所需的布局。在它下面,我绘制了我尝试过的 html 层次结构。

enter image description here

事实上,我已经尝试过创建 <h1> 的子项与

width: 100vw;
position: relative;
left: 50%;
transform: translate(-50%);

但是:

  1. 因为页面有 z-index: -1; , 对于一些奇怪的错误我无法点击相对定位的链接
  2. 我不想使用 vw因为浏览器支持而联合起来。
  3. 我仍然无法将背景扩展到顶部。

<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;}

JS Fiddle

最佳答案

两个建议:

将 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-xbakcground-size: cover。但这取决于图像的设计方式。

关于html - 使用 CSS 延伸到页面边缘和顶部的标题背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920524/

相关文章:

CSS:删除通用选择器应用的边框

css - IE11 : Add extra space above anchor tags

jquery - 随着窗口大小的变化自动重新调整 jquery ui-dialog 的位置

html - 在 css 中制作带虚线边框的圆圈并在悬停时设置动画

html - 为什么我的背景图片不显示?

html - 将字段集与骨架框架一起使用的问题

javascript - 从左到右动画 div

javascript - jQuery 在选择器中合并变量

jquery - csstoggleClass 无法正常工作

Android,向 TextView 添加不同数量的可点击跨度