簡體   English   中英

居中圖像左上角的疊加元素

[英]Overlay element at top-left corner of centered image

我有一個使用 flexbox 當前位於屏幕中心的圖像:

.center-flex {
    display: flex;
    justify-content: center;
}

<div class="center-flex">
    <img id="revealImage">
</div>

我正在嘗試動態創建一個需要放置在左上角的div 我嘗試了以下方法將計算機left在圖像上,但它無法正常工作,因為它返回auto

const revealImage = document.getElementById('revealImage');

const left = window.getComputedStyle(revealImage,null).getPropertyValue('left');

let square = document.createElement('div');
square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
square.style.left = left;

console.log('left: ' + left);

這會產生一個正確覆蓋的紅色框,但它居中而不是設置在左側。

顯示渲染輸出

我會在 html 中建議一種不同的方法,通過使用picture<\/code>元素來包裹紅色方塊。

例如,

html<\/code> :

<div class="center-flex">
    <picture>
        <img id="revealImage">
    </picture>
</div>

我認為你犯了一個小錯誤(如果我沒有弄錯的話):

似乎這是錯誤的:

square.style.left = left;

做:

square.style.left = 0;

這樣對嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM