0

I used example from tutorial https://www.w3schools.com/howto/howto_css_image_text.asp

I don't understand why my text aligned to bottom right corner of outer div instead of image, can some one explain why? and how to resolve this issue without having fixed height container.

fiddle: https://jsfiddle.net/axhqn2b5/2/

HTML

<div class="container">
   <img src="http://via.placeholder.com/200x50"> 
   <div class="bottom-right">Bottom Right aligned to outer container, why?</div>
</div>
<br/>
<div class="container">
  <div class="box">line<br/>line<br/>line<br/>line<br/>line</div>
  <div class="bottom-right">Bottom Right aligned to inner box</div>
</div>

CSS

.container {
    position: relative;
    border: black 1px solid;
}
.bottom-right {
    position: absolute;
    bottom: 0;
    right: 0;
    background: lightgreen;
}
img {
    width: 100%; 
    border: red 1px solid;
    box-sizing: border-box;
}
.box {
    border: red 1px solid;
}

It shows that image height is less then outer container height. I can use text "bottom" attribute to align it, but may be there is better solution.

Xoog
  • 908
  • 1
  • 10
  • 30
  • `position: absolute` means it's placed relative to the nearest positioned _ancestor_. So it will never be positioned relative to a sibling. – Jesse Feb 02 '18 at 09:07

2 Answers2

2

You need to change the image diplay property.

Add:

img {
    display: block;
}

The image by default is rendered as an inline element.

gentian
  • 148
  • 1
  • 2
  • 9
0

the difference you see i because of the whitespace below the image.

to fix that just add vertical-align:top; to the image

img {
    width: 100%; 
    border: red 1px solid;
    box-sizing: border-box;
    vertical-align:top; /*add*/
}

and now your text will be at the same position.

both examples you gave are actually positioned at bottom right of .container

Dirk
  • 831
  • 6
  • 13