简体   繁体   English

使用JavaScript调整元素大小时如何刷新自动边距?

[英]How do I refresh auto margins when I resize an element using Javascript?

I have a DIV in the center of my page which has margin-left and margin-right both set to auto. 我在页面的中心有一个DIV,其中左边距和右边距都设置为auto。 I want to be able to enlarge or shrink that DIV. 我希望能够放大或缩小该DIV。 Unfortunately when I do so, the position of it on the screen does not change, meaning that it is no longer centered. 不幸的是,当我这样做时,它在屏幕上的位置没有改变,这意味着它不再居中。

<div id="content" style="margin-left:auto;margin-right:auto;width:240px">
  <p>Lots of text</p>
</div>

Meanwhile elsewhere: 同时在其他地方:

$("#content").width(480);

At this point, I get my div no longer centered, but overbalanced to the right. 此时,我的div不再居中,而是向右过度平衡。 Similarly if I set the width smaller than 240, it then becomes too far to the left. 类似地,如果我将宽度设置为小于240,则宽度将变得太左。

How do I ensure that my margins actually adjust when the width changes? 当宽度改变时,如何确保边距实际调整? Needs to work in all modern browsers. 需要在所有现代浏览器中工作。

The div ist still centered. 仍然居中。 Just the text is aligned left. 只是文本左对齐。

Try this: 尝试这个:

<div id="content" style="margin-left:auto;margin-right:auto;width:240px;border:1px solid red;text-align:center">
  <p>Click here</p>

$('p').click(function(){$("#content").width(480)})

- http://jsfiddle.net/nvzaw/1/ -http://jsfiddle.net/nvzaw/1/

I have posted an answer to a similar problem (about window resize) here 我已经发布回答类似的问题(约窗口大小调整) 在这里

Maybe this helps you! 也许这对您有帮助!

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

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