简体   繁体   English

如果将divs边距设置为自动,如何获得以像素为单位的divs左右边距?

[英]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. 此方法计算元素宽度和容器中剩余宽度之间的剩余空间,这就是margin: auto应该做。 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. 您可以使用$(".container").offset()获得左侧位置。 So, the left position of the current control minus(-) current control gives you the necessary output. 因此,电流控制的左侧位置减去(-)电流控制将为您提供必要的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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