Search code examples
csspositionabsoluteoverlapping

CSS overlapping elements by preserving parent size


I want to overlap some elements without using position: absolute. The reason therefore is that I have several vertical sections (which should not overlap) containing elements which overlap. The problem is, I cannot know beforehand whether the overlapping or the overlapped element has the bigger size. If one of those would receive a position: absolute it would be taken out of flow and therefore the parent container would not be sized accordingly and the sections would overlap. I have already found this question but nobody seemed to answer the question. Here is an example: http://jsfiddle.net/nNhtU/


Solution

  • If it's ok to use jQuery, this can be done quite easily. Set the overflow property of the parent element to scroll:

    .designer-question {
        overflow: scroll;
    }
    

    And then you can set the height of each .designer-question to the height of its img using a simple each loop:

    $('.designer-question').each(function () {
        var $el = $(this);                   // Get jQuery of each designer question
        var $backImg = $('.back img', $el);  // Get background image
        $el.css('height', $backImg.height());
    });
    

    I've applied this to your jsfiddle to demonstrate: http://jsfiddle.net/jfdPb/1/