塊級子元素寬度溢出父元素,強制不換行


對於字符串,可以通過 white-space:no-wrap 來控制,溢出父元素時,不換行,但是對於塊級元素,並沒有這樣的屬性,如圖:

image

CSS:

    .par {
        width: 200px;
        height: 100px;
        background: pink;
    }

    .child {
        display: inline-block;
        height: 40px;
        opacity: 0.5;
    }

    .child:nth-child(1) {
        width: 100px;
        background: lightblue;
    }

    .child:nth-child(2) {
        width: 110px;
        background: lightgreen;
    }

HTML:

<div class="par">
        <div class="child">
        </div>
        <div class="child">
        </div>
</div>

子元素,110px+110px+間隙 超出了父元素 200px 的寬,就自動換行了,即使換成 float 也是一樣的情況,這種情況下,要強制子元素不換行,需要在

1、.child 和 .par 中間加一層 div,寬度高於 .child 之和,

2、給 .par 設置 overflow:hidden

示例:

image

CSS:

    .par {
        width: 200px;
        height: 100px;
        background: pink;
        overflow: hidden;
    }
    
    .brother {
        width: 220px;
    }

    .child {
        display: inline-block;
        height: 40px;
        opacity: 0.5;
    }

    .child:nth-child(1) {
        width: 100px;
        background: lightblue;
    }

    .child:nth-child(2) {
        width: 110px;
        background: lightgreen;
    }

HTML:

    <div class="par">
        <div class="brother">
            <div class="child">
            </div>
            <div class="child">
            </div>
        </div>
    </div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM