search

Home  >  Q&A  >  body text

Align the inline-block DIV element to the top of the container element

<p>When two <code>inline-block</code>'s <code>div</code> have different heights, why doesn't the shorter one align with the top of the container? (<strong>DEMO</strong>): </p> <p><br /></p> <pre class="brush:css;toolbar:false;">.container { border: 1px black solid; width: 320px; height: 120px; } .small { display: inline-block; width: 40%; height: 30%; border: 1px black solid; background: aliceblue; } .big { display: inline-block; border: 1px black solid; width: 40%; height: 50%; background: beige; }</pre> <pre class="brush:html;toolbar:false;"><div class="container"> <div class="small"></div> <div class="big"></div> </div></pre> <p><br /></p> <p>How do I align a small <code>div</code> to the top of its container? </p>
P粉682987577P粉682987577490 days ago407

reply all(2)I'll reply

  • P粉786432579

    P粉7864325792023-08-22 10:06:59

    You need to add the vertical-align attribute to both child divs.

    If .small is always shorter, just apply this property to .small. However, this property should be applied to .small and .big if either one is likely to be the highest.

    .container{ 
        border: 1px black solid;
        width: 320px;
        height: 120px;    
    }
    
    .small{
        display: inline-block;
        width: 40%;
        height: 30%;
        border: 1px black solid;
        background: aliceblue; 
        vertical-align: top;   
    }
    
    .big {
        display: inline-block;
        border: 1px black solid;
        width: 40%;
        height: 50%;
        background: beige; 
        vertical-align: top;   
    }

    Vertical alignment affects in-row or table cell boxes, and this property has many different values. See https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.

    reply
    0
  • P粉744831602

    P粉7448316022023-08-22 00:58:11

    Because by default, vertical-align is set to baseline.

    Use vertical-align:top instead:

    .small{
        display: inline-block;
        width: 40%;
        height: 30%;
        border: 1px black solid;
        background: aliceblue;   
        vertical-align:top; /* <---- this */
    }

    http://jsfiddle.net/Lighty_46/RHM5L/9/

    Or as @f00644 said, you can also apply float to child elements.

    reply
    0
  • Cancelreply