简体   繁体   中英

Why span aligned beyond the bottom and how may I manipulate it

Please, explain me WHY this is happening - why the text of the span is aligned beyond the bottom of the image - and how may I actually manipulate the span to move it in x and y coordinates, because manipulating it with padding and margin doesn't work on it. I can make it work eventually, but there must be some simple way of doing this.

HTML:

<div class="cnt">
  <img src="http://ecx.images-amazon.com/images/I/41jlGA2RzmL._SS40_.jpg"><span>zzz</span>
</div>

CSS:

html,body,.cnt,img,span {
  margin: 0;
  padding: 0;
}
.cnt {
  width: 300px;
  border: 1px solid #777;
}
.cnt img {
  background: #090;
}
.cnt span {
  margin-top:-20px;
  background: #333;
}

https://jsfiddle.net/kcepLrhx/

The default vertical-align of an img is to align at the baseline. https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

To change it, change vertical-align on the img

 html,body,.cnt,img,span { margin: 0; padding: 0; } .cnt { width: 300px; border: 1px solid #777; } .cnt img { background: #090; vertical-align: middle; } .cnt span { margin-top:-20px; background: #333; } 
 <div class="cnt"> <img src="http://ecx.images-amazon.com/images/I/41jlGA2RzmL._SS40_.jpg"><span>zzz</span> </div> 

You can actually set the span position to absolute, then you'll have the control over the x and y coordinates with the margin propiety. Make sure that cnt 's position is relative , which is the default position of any element you create.

For example:

 html,body,.cnt,img,span { margin: 0; padding: 0; } .cnt { width: 300px; border: 1px solid #777; position: relative; /* It is the default value */ } .cnt img { background: #090; } .cnt span { background: #333; margin-top: 15px; margin-left: 15px; position: absolute; /* span position is absolute to the div position */ } 
 <div class="cnt"> <img src="http://ecx.images-amazon.com/images/I/41jlGA2RzmL._SS40_.jpg"><span>zzz</span> </div> 

https://jsfiddle.net/Lgyw4co2/

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