如何实现背景图居容器右侧、左侧悬浮文本框叠加图片的响应式布局?
解决方案
要实现背景图居右、文本框左侧悬浮重叠且适配移动端的效果,只需对现有CSS做如下调整:
核心修改点
- 调整容器背景的定位与尺寸,让背景图固定在右侧且高度填满容器
- 调整flex布局对齐方式,让文本框靠左展示
- 添加媒体查询,针对移动端重新适配背景与文本框布局
完整代码
CSS
.container { background-image: url("https://houniqueconstruction.com/wp-content/uploads/2023/02/peng-chen-WFgSotZQECo-unsplash-copy-1024x803.jpg"); background-repeat: no-repeat; background-position: right center; /* 背景图靠右垂直居中 */ background-size: auto 100%; /* 高度匹配容器,宽度自适应 */ min-height: 700px; position: relative; padding-left: 5%; /* 避免文本框贴紧屏幕左侧 */ } .flexbox { display: flex; justify-content: flex-start; /* 文本框靠左排列 */ align-items: center; min-height: 700px; } .text-box { max-width: 350px; background: #f6f6f6; padding: 30px 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: relative; z-index: 1; /* 确保文本框在背景图上方 */ } /* 移动端适配 */ @media (max-width: 768px) { .container { background-size: cover; /* 背景图覆盖整个容器 */ background-position: center; /* 背景图居中显示 */ padding-left: 0; min-height: auto; } .flexbox { min-height: auto; padding: 40px 20px; justify-content: center; /* 文本框居中 */ } .text-box { max-width: 100%; /* 文本框占满屏幕宽度 */ } }
HTML
<div class="container"> <div class="flexbox"> <div class="text-box"> <h1>Complete Remodeling</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrude dolore magna.</p> <a>CONTACT US</a> </div> </div> </div>
效果说明
- 桌面端:背景图固定在容器右侧,高度填满容器;文本框靠左悬浮,与背景图自然重叠,且通过
z-index确保文本框在前景 - 移动端:背景图全屏覆盖居中显示,文本框占满屏幕宽度并居中排列,避免小屏幕下重叠导致的可读性问题
内容的提问来源于stack exchange,提问作者John Holliday
相关产品推荐
相关产品推荐

