![](/img/trans.png)
[英]CSS - How to center a div relative to a background image positioned as cover
[英]Center cover image to match with background
我有一張大小為:封面的背景圖片,我也剪掉了這張圖片的一部分,使其更輕並位於其他 div 的頂部。
結構如下(灰色 - 背景,紫色 - 此背景的一部分被剪掉並位於頂部,粉紅色 - 菜單部分(!)被該圖像覆蓋,因此我可以與之交互) 問題是我希望在調整瀏覽器窗口大小時封面圖像始終與其背景匹配
我手動設置了頂部和左側以匹配背景,但是當高度/寬度比率改變時它仍然沒有
<section class="main">
<div class="container">
<div class="content">
Main page content
</div>
<side-container></side-container>
</div>
<img class="cover-image" src="../../assets/img/img-shoes@2x.png" alt="sneakers">
</section>
薩斯:
.main
background-color: black
background-image: url('../../assets/img/bg.png')
background-size: cover
background-repeat: no-repeat
overflow: hidden
.cover-image
position: absolute
z-index: 30
width: 31vw
height: auto
left: 4.5vw
top: 15vh
bottom: 0
right: 0
margin: auto
由於缺少演示鏈接或在線版本,我無法弄清楚問題所在。
但我認為這對你有用:
.cover-image
position: absolute
z-index: 30
width: 31vw
height: auto
top: 50%
left: 50%
transform: translate( -50%, -50% )
margin: auto
它使用transform
根據其寬度和高度而不是父級來改變<img>
的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.