简体   繁体   中英

Why images are aligned to the bottom of a div?

In the following example, the image is aligned to the bottom of the parent container:

HTML:

<div>
  <img src="https://www.google.com/images/srpr/logo11w.png">
  <div>A B C D E F G H I J K L M N O P Q R S T U V W X Y Z</div>
</div>

CSS:

img{
    height: 2em;
    top: 0px;
}

div div {
    width: 5em;
    display: inline-block;
}

Can use this JSFiddle for reference: https://jsfiddle.net/9nLyr6f6/2/

  1. I was just curious to know what the logic is for that? What rule applies?
  2. How to change it and have the image at the top?

Because the default vertical alignment for inline elements is baseline.

See https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

To change it, set the vertical-align property on the image to something other than its default.

 img{ height: 2em; top: 0px; vertical-align:top; } div div { width: 5em; display: inline-block; } 
 <div> <img src="https://www.google.com/images/srpr/logo11w.png"> <div>ABCDEFGHIJKLMNOPQRSTU VWXY Z</div> </div> 

The image and the inner div are both inline-block elements, which are aligned on the baseline of the text. So the outer div actually contains one line of 'text'. This line doesn't contain actual text, but only two blocks: the image and the inner div. Both are aligned on the base line.

You can see this especially if you add some text and a border. The image aligns with the base line of the text.

 img{ height: 2em; top: 0px; border: 1px solid green; } div { border: 1px solid blue; } div div { width: 5em; display: inline-block; border-width: 0px; } 
 <div> A <img src="https://www.google.com/images/srpr/logo11w.png"> B <div>ABCDEFGHIJKLMNOPQRSTU VWXY Z</div> Cxyz </div> 

You can solve this by adding vertical-align: top to the image:

 img{ height: 2em; top: 0px; vertical-align: top; } div div { width: 5em; display: inline-block; } 
 <div> <img src="https://www.google.com/images/srpr/logo11w.png"> <div>ABCDEFGHIJKLMNOPQRSTU VWXY Z</div> </div> 

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