简体   繁体   中英

How can I get a divs left and right margin in pixels if the divs margin is set to auto?

jQuery(".container").css("margin-right")给我: auto ,而我想要52px52

你可以得到当前宽度减去当前块的宽度再除以2

This method calculates the remaining space between an elements width and the remaining width in the container, which is what margin: auto SHOULD do. This does NOT necessarily return the margin that the element has.

var parentwidth = $('.container').parent().width();
var childwidth = $('.container').width();
var marginLeft = (parentwidth-childwidth)/2;

NB: if there is any padding this must be compensated for.

You can use $(".container").offset() to get the left position. So, the left position of the current control minus(-) current control gives you the necessary output.

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