简体   繁体   中英

CSS - Stop table cell background overflowing outside of its width/height

HTML/CSS:

<header>
    <div id="left" class="cell"></div>
    <div id="centre" class="cell"></div>
    <div id="right" class="cell"></div>
</header>

header {
    height: 18%;
    background-color: #0099ff;
    display: table;
    width: 100%;
}

.cell {
    display: table-cell;
}

#left {
    width: 20%;
    background: url("../img/3lines.png") no-repeat center center;
    background-size: 25% auto;
}

#centre {
    width: 60%;
    background: url("../img/logo.png") no-repeat center center;
    background-size: 100% auto;
}

#right {
    width: 20%;
    background: url("../img/3lines.png") no-repeat center center;
    background-size: 25% auto;
}

Images of what's happening, this is what is happening now with a small portrait screen, this is perfect:

在此处输入图片说明

This however is not perfect, when viewed in landscape the logo flows outside of its cell:

在此处输入图片说明

How can I stop the logo from overflowing outside of its table cell?

background-size: 100% auto; is stretching your background to fill it's parent horizontally. As the width:height aspect ratio of the element increases beyond that of the background image, the image is forced to grow vertically beyond it's container in order to fill that 100% width.

What you want is just background-size: contain; , as that will constrain it to the size of the element and make it as large as possible without stretching it.

div{
    background: url("https://www.google.com/images/srpr/logo11w.png") no-repeat center center;
    background-size: contain;
    height: 200px;
}

JSFiddle

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