Search code examples
csspositioning

stretch an element according to the content or to the parent element


Is there a non javascript way to stretch an element either in relation to its parent (if the content is too short) or following the content. Here are three images to explain the topic:

little content
This is a divpositioned absolute with top, bottom etc at 20px

lot content
This is the some situation with more content "breaking" the div which is not the way it should be.

Should look like this
You get the idea?


Solution

  • Sure, don't position: absolute the inner div.

    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #outer {
            background: #ccc;
            padding: 20px;
            margin: 20px;
            width: 200px;
            height: 100px;
            overflow-y: auto;
        }
        #inner {
            background: white;
            border: 1px black solid;
            box-sizing: border-box;
            min-height: 100%;                
        }
    </style>
    <div id=outer>
        <div id=inner>
            <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum
                tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas
                semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien
                ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean
                fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec
                non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque
                egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan
                porttitor, facilisis luctus, metus</p>
        </div>
    </div>
    

    Live Example