开发者

jQuery, toggling div, CSS spacing issue

开发者 https://www.devze.com 2022-12-20 06:30 出处:网络
I have this markup: <div class=\"myToggledDiv\"> <div>content</div> </div> <div style=\"margin-top: 10px;\">

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="myTog开发者_开发百科gledDiv">
    <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?


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 }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号