简体   繁体   中英

Image width in dynamic height container does not affect container width

I have a div with text, and I want to create a square space on the right side, after text.

I can't just set a fixed padding-right because I want to make it work for any text size.

This is what I have:

<div class="wrapper">
    <table class="size-maker" cellpadding="0" cellspacing="0">
        <tr>
            <td>Hello!</td>
            <td class="ratio-1x1">
                <!-- just 1x1 transparent image to maintain 1x1 aspect ratio when resized -->
                <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCB1jYAAAAAIAAc/INeUAAAAASUVORK5CYII=" />     
            </td>
        </tr>
    </table>
    <div class="content"></div>
</div>

<style type="text/css">
    .wrapper {
        background: #0055cc;
        position: relative;
        display: inline-block;
    }

    .size-maker {
        font-size: 20px;
        color: white;
    }

    .size-maker .ratio-1x1 {
        height: 100%; /* need for FireFox */
    }
    .size-maker .ratio-1x1 img {
        height: 100%;
        background: rgba(0,0,0,0.5);
    }

    .content {
        background: #00DD00;
        position: absolute;
        top: 150%;
        left: 0;
        width: 100%;
        height: 100%;
    }
</style>

<br/><br/><br/><br/><br/>
<h3>Task</h3>
<p>Black square should be inside of blue, and green square should have the size of both blue+black</p>
<p style="color: gray;"><em>This should work for any font size <b><code>.size-maker { font-size: ...px; }</code></b></em></p>

Link to sourcebox

Use EM for relative padding.

Sourcebox

I just added padding-right:1.15em to .size-maker

.size-maker {
    font-size: 20px;
    color: white;
    padding-right: 1.15em;
}

Where 1em = 100% of element or parent element font-size.

In this scenario 1.15em will be 115% of 20px (font-size).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM