2

I want to align image and text in center . Please see my html code

.normal-div-border {
  border: 1px solid #0e0d0d1a;
  margin-top: 10px;
  padding: 11px;
}

.j-div {
  overflow: hidden;
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

.j-icon {
  float: left;
}

.img-span {
  float: left;
  margin-top: 16px;
}
<div class="normal-div-border">
  <div class="j-div">
    <span class="img-span">
   <img src="https://cdn2.iconfinder.com/data/icons/superheroes-set/128/ironman-2-32.png" class="j-icon">
   </span>
    <h2 class="new-h2"> Test Heading </h2>
  </div>
  <p>testing...................................</p>

</div>

Hear what i need is i need to arrange test heading and and image in center . Currently there is a gap between that image and new-h2. How can fix this .

Actually for fixing this i use

.j-div{
             overflow:hidden;
             width:50%;
             margin:0 auto;
             text-align:center;
         }

But this is only fixing the text , not the image .

Please help .

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
Abilash Erikson
  • 341
  • 4
  • 26
  • 55

1 Answers1

4

Instead of float:left Use display:inline-block;

.normal-div-border {
  border: 1px solid #0e0d0d1a;
  margin-top: 10px;
  padding: 11px;
}

.j-div {
  overflow: hidden;
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

.j-icon, .new-h2  {
  display:inline-block;
  vertical-align:middle;
}

.img-span {
  display:inline-block;
  margin-top: 16px;
}
<div class="normal-div-border">
  <div class="j-div">
    <span class="img-span">
   <img src="https://cdn2.iconfinder.com/data/icons/superheroes-set/128/ironman-2-32.png" class="j-icon">
   </span>
    <h2 class="new-h2"> Test Heading </h2>
  </div>
  <p>testing...................................</p>

</div>
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
  • Thank you friend . This is working . But how you understand this ? Could you please explain what is the idea behind this . – Abilash Erikson Apr 18 '17 at 12:49
  • `text-align:center` works on `inline` elements, and `float:left` was making `span` and `h2` as `block` element. Read [this post](http://stackoverflow.com/questions/8969381/what-is-the-difference-between-display-inline-and-display-inline-block) and [w3c doc](https://www.w3.org/TR/CSS2/visuren.html#inline-boxes) to understand `inline-boxes`. – Abhishek Pandey Apr 18 '17 at 12:59