1
  • I created four divs
  • I added a span to one of the divs
  • However, when I added the span, it moves vertically downwards from its normal position
  • I do not understand why this is happening

.div {
  width: 100px;
  height: 50px;
  border: 2px dotted #686868;
  border-radius: 10px;
  display: inline-block;
  margin: 10px;
}
<div class="div" id="a1"><span>xyz</span></div>
<!-- this div element is moving from its original position -->
<div class="div" id="a2"></div>
<div class="div" id="a3"></div>
<div class="div" id="a4"></div>
PeterJames
  • 1,137
  • 1
  • 9
  • 17
  • Is there a reason you're using `display: inline-block` instead of flexbox? – Dai Jul 24 '22 at 09:36
  • I was learning display:inline-block and tried to implement on div . I could do with Flexbox using display:flex and flex-direction:row to the main container and it will display. However I thought what is the reason why the div is moving when I insert span element in it. This behaviour is quite abnormal – Rahul Singh Jul 24 '22 at 09:38
  • Hint: when you use `inline-block` and the element is taller than the parent _flow container_'s `line-height` you'll encounter unexpected-but-actually-very-well-defined vertical-alignment issues like this. – Dai Jul 24 '22 at 09:41
  • How should I fix this Dai. Is there any solution for the given code – Rahul Singh Jul 24 '22 at 09:43
  • That depends on what end-result you want. If you want to have some boxes in a line containing text then you should use `flex` instead of `inline-block`. You _can_ make it work as-is by playing with `vertical-align:` and `line-height:` but it feels like a hack to me because you end-up abusing a `flow` context. – Dai Jul 24 '22 at 09:44
  • when I added overflow:hidden to my inline-block element it worked. I don't know the reason but someone mentioned about overflow:hidden in the article.https://stackoverflow.com/questions/9273016/why-is-this-inline-block-element-pushed-downward – Rahul Singh Jul 24 '22 at 13:21

0 Answers0