jQuery, toggling div, CSS spacing issue

被刻印的时光 ゝ 提交于 2020-01-24 15:47:10

问题


I have this markup:

<div class="myToggledDiv">
    <div>content</div>
</div>

<div style="margin-top: 10px;">
    content
</div>

Via jQuery, I'm doing a .slideToggle to show/hide the top div.

I'd like there to be the 10px space between the two divs at all times, whether collapsed or expanded.

The behavior, however is that as the top div slides down, the 10px margin remains but as soon as the top div is finished sliding down the 10px margin disappears. It appears to be a margin collapse issue perhaps.

The solution I came up with is this:

<div class="myToggledDiv">
    <div>content</div>
</div>

<div style="font-size: 1px">&nbsp;</div>

<div style="margin-top: 10px;">
    content
</div>

The &nbsp; is the key as there needs to be content in the div to 'separate' the two and retain the 10px of margin.

I tried the .clearfix:after approach as well, but that doesn't work in this scenario, so perhaps this is a jQuery centric issue. Has anyone ran into this and found a more elegant solution than the extra div?


回答1:


Believe it or not, you just need to add a 1px padding to the top of the parent container. The problem is, at the end of slideToggle the first div is set to display:none which causes the second div to be smack dab against the parent. Now, its just a CSS bug. If there is no padding set on the parent item, the child items margin will go outside of the parent, and push both items down. By applying a 1px margin to the parent element, you force the margin to stay inside the element:

<body style="padding-top: 1px">
  <div class="myToggledDiv">
      <div>content</div>
  </div>

  <div style="margin-top: 10px;">
      content
  </div>
</body>

Obviously, you want to remove all of those inline styles and use a separate stylesheet and id's/classes as needed.

If you need to offset the extra padding (depending on your layout) you might just be able to use this:

{ margin-top: -1px; padding-top: 1px }



回答2:


Somewhat of an odd workaround, but you can set the following rules for the second div:

{ position:relative; top:10px; }

Online demo: http://jsbin.com/enala/edit

I would also encourage you to consider Doug's Answer. If setting a padding on your parent container produces undesired results, you could fall back on this solution as an alternative.



来源:https://stackoverflow.com/questions/2283538/jquery-toggling-div-css-spacing-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!