要解决背景图片重叠标题和页脚的问题,并使文本居中于中间,可以使用CSS的position属性来定位元素。以下是一个示例代码,演示如何实现这个效果:
HTML代码:
背景图片重叠标题和页脚
标题
文本内容
CSS代码(styles.css):
body {
margin: 0;
padding: 0;
background-image: url('background.jpg');
background-size: cover;
}
.container {
position: relative;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
h1 {
font-size: 36px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 20px;
}
p {
font-size: 24px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
}
footer p {
font-size: 18px;
color: white;
}
在这个示例中,我们通过设置容器元素的position为relative,并使用flex布局将标题和文本内容居中于容器中间。背景图片设置在body元素上,并使用background-size: cover;确保图片铺满整个页面。
页脚使用position:absolute;将其固定在页面底部,同时使用text-align: center;使文本居中显示。
通过在标题和文本内容的背景色中使用rgba()来设置半透明的背景色,来实现背景图片能够显示出来但不遮挡文本内容。
你可以将上述代码保存为HTML文件,并将相应的背景图片命名为background.jpg(或者根据自己的需要修改代码中的图片路径),然后在浏览器中打开HTML文件,即可看到效果。
下一篇:背景图片周围出现了空白