How to force parent div to expand by child div width/padding/margin/box?

后端 未结 3 1084
生来不讨喜
生来不讨喜 2020-12-28 14:52

I want to expand div parent with child div but I don\'t know if that\'s possible and how to do it.

\"enter

相关标签:
3条回答
  • 2020-12-28 14:55

    You cannot use % and expect box to overflow, else it never ends 100% turns 120%, but then 120% of 120%, becomes .. and so on. forget this idea, it cannot work.

    Your CSS request is incoherent.

    Beside, to see an element to grow wider than window, one of the parent must be able to behave this way, mostly , content overflow and remain visible. (html/body or parent)

    as far as i know only:

    display:
    
    1. table
    2. inline-table
    3. table-row
    4. table-cell

    Can let container grow as much as content does.

    0 讨论(0)
  • 2020-12-28 14:56

    Your problem is this:

    div.two {
            background-color: green;
            width: 120%;
    }
    

    You are telling the child to be 120% the width of the parent, which is to say, the entire width plus 20% more. Make it 100% and you should get the expected result..

    0 讨论(0)
  • 2020-12-28 15:08

    The key solution to your problem is to use display:inline-block;

    HTML

    <div class="page">
        <div class="one">One</div>
        <div class="two">Two</div>
    </div>
    

    CSS

    body {
        background: gray;
    }
    div.page {
        color: white;
        background: black;
        margin: auto;
        padding: 1em;
        display:inline-block;
    }
    div.one {
        background-color: red;
        width: 10em;
        display:inline-block;
    }
    div.two {
        background-color: green;
        width: 40em;
        display:inline-block;
    }
    

    Here is the working fiddle

    0 讨论(0)
提交回复
热议问题