简体   繁体   中英

jquery center div at point

I am creating a div using jquery and I am trying to center it at a specific point. The text in the div is dynamic, and it's not centered in a particular parent html, but rather I want to center it on just a specific point.

So basically I have

var centerX = 100; // dynamically computer in my code
$('<div/>').text('sometext').css({'left': (centerPointX - $('#mydiv').width() / 2) + 'px'});

But the width of mydiv is not known until it is rendered, so I'm not sure how to go about centering at the x point. Do I need an outer container in which to center in relative to?

Firstly $('#mydiv') only gets the element if it is available in the DOM .

So you would first be required to inject the element into the DOM and then access the width property . Otherwise it will be 0 when you try to access the width property of the element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM