簡體   English   中英

使用JS將div水平居中而沒有寬度

[英]Center div horizontally without width with JS

我正在編碼我的研究生作品,但無法將div與更改內容(圖像上傳)居中。

在我的腳本中,我創建<img id="uploaded">並將已上傳的圖像插入其中,並將此<img>插入<div id="canvas"></div>

在我的CSS中:

#canvas {
    position: absolute;
    left: 50%;
    z-index: 500;
}

我試過了 :

var canvaswidth = document.getElementById('uploaded').width;

用於獲取img寬度,我想為div居中添加一個負的左邊距。

我試過了 :

document.getElementById('canvas').style.marginLeft = - canvaswidth / 2;

但這是行不通的。 你能幫我使它工作嗎?

您需要單位:

document.getElementById('canvas').style.marginLeft = - canvaswidth /2 + 'px';

但是,您可以使用“絕對居中”:

#canvas {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
}

並將width設置為所需的值:

document.getElementById('canvas').style.width = canvaswidth + 'px';

暫無
暫無

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

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