html - 居中固定容器背景
问题描述
我想创建一个具有固定背景的标题。所以我定义了以下属性:
header {
margin: 0;
padding: 0;
width: 100%;
height: 300px;
display: block;
background-image: url('...');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
background-attachment: fixed;
}
现在我有以下问题。目前,背景根据屏幕宽度和高度居中。由于标题位于顶部,因此标题的实际背景只是图像的顶部。此外,每次更改屏幕高度时,标题图像部分都会更改,这不是我的目标。
我希望图像在标题中居中(图像的中心位于标题的中心,但前提是我没有向下滚动)。此外,标题图像部分仅在我更改标题宽度、高度或屏幕宽度时才应更改,但在屏幕高度更改时不会更改。
解决方案
你可以依靠vh
unit 结合一些calc()
. 中心最初50vh
是150px
从顶部开始的,因此我们需要翻译50vh - 150px
. cover
如果您希望图像在屏幕高度变化时不发生变化,但它可能不会像您想要的那样呈现,您也应该摆脱它。
我替换300px
为100px
演示。
.header {
height:100px;
border:1px solid;
background:
url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px)) fixed;
}
.not-fixed {
background-attachment:initial;
background-position:center;
margin-top:20px;
}
body {
min-height:200vh;
margin:0;
}
<div class="header">
</div>
<div class="header not-fixed">
</div>
随着使用cover
.header {
height:100px;
border:1px solid;
background:
url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px))/cover fixed;
}
.not-fixed {
background-attachment:initial;
background-position:center;
margin-top:20px;
}
body {
min-height:200vh;
margin:0;
}
<div class="header">
</div>
<div class="header not-fixed">
</div>
您可以清楚地看到第一张图像如何与第二张图像完全一样居中,而无需fixed
要获得有关计算的更多详细信息,请检查:Using percent values with background-position on a linear gradient(组合像素和百分比值部分)
推荐阅读
- python-3.x - I cannot read csv file as pandas dataframe (anymore)
- r - Why Rmarkdown does not render fig.caption for github_document?
- reactjs - Set state and change local variable while ESLint is preventing to do
- r - checking website status of multiple urls using lapply- error handling
- python - From scatter plot to 2D numpy array with binary entries in Python
- maven - How to properly set the output file structure with maven assembly
- c++ - 无法将参数 8 从“int”转换为“cv::HOGDescriptor::HistogramNormType”
- php - Oracle XE returns false fetching a table with 1 milion of lines using PHP
- javascript - 使用`Map`我如何编写一个将华氏值数组转换为摄氏度的函数?
- java - 从 HashSet 中的对象返回连接某些字段的字符串