开发者

CSS: Suppressing negative margins of child elements

I have a parent element (e.g. a div) which surrounds some dynamic content. I would like the parent div to fully contain the child elements in as many circumstances as possible.

One problem is child elements with negative margin settings, which cause the child element to be displayed outside of the parent element (and also cause the parent element not to be of the desired size).

So

  1. Is there any css trick that can be applied to the parent in order to suppress the negative margins in the child elements (e.g. without havi开发者_如何学运维ng to modify the styles on the child).

  2. Failing that, is there anyway to detect via javascript whether a particular element has overflowing content? (and in which direction and to what degree the content is overflowing?)


Did you try to put a class to the parent like:

.parentDiv > * {
  margin:0 !important;
}

To have the parent with the desired height, you need to set some css too:

.parentDiv{
    overflow:hidden;
    position:relative;
    background:#DFE;
    padding:5px;
 }


There is a javascript method of handling this, but it's certainly not as clean as @Mic's CSS solution. I haven't completely tested this, and you may need to add some support for various padding/margin adjustments, but it would get somebody started if a JS-solution was the only option. Using prototype.js (jquery would be similar, but plain javascript will be very.. stretchy):

function checkOverflow (child) {
  child = $(child);
  if (child.descendants().any()) {
    child.getElementsBySelector("> *").each(function(e) {
      checkOverflow(e);
    });
  }

  var parent = child.up();

  var child_left = child.cumulativeOffset()['left'], child_top = child.cumulativeOffset()['top'];
  var child_height = child.getDimensions()['height'], child_width = child.getDimensions()['width'];

  var parent_left = parent.cumulativeOffset()['left'], parent_top = parent.cumulativeOffset()['top'];
  var parent_height = parent.getDimensions()['height'], parent_width = parent.getDimensions()['width'];

  if (child_top < parent_top) {
    if (child_left < parent_left) {
      // adjust element style here
    } else if (child_left > parent_left + parent_width) {
      // adjust element style here
    }
  } else if (child_top > parent_top + parent_height) {
    if (child_left < parent_left) {
      // adjust element style here
    } else if (child_left > parent_left + parent_width) {
      // adjust element style here
    }
  }
}

My general feeling, though, is that you should only do this if it can't be explicitly done through CSS.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜