Tom Maxwell
Tom Maxwell

Reputation: 9573

Text-align:center not working on image inside div

I have a div in my app containing profile information like name, account #, and profile picture. For some reason the profile picture won't center even though I've tried the text-align:center trick. Here's my HTML:

<div id="profile-heading">
    <img alt="6dbepurq" src="http://anymarket.s3.amazonaws.com/users/avatars/000/000/015/medium/6dBEpuRQ.jpeg?1406690559">
    <h2>Tom Maxwell</h2>
    <p id="school">University of California, Berkeley</p>
    <p>User #15</p>
</div>

And the CSS for the #profile-heading div looks like this:

 #profile-heading {
  text-align:center;
  margin-top:50px;
  img{
    border-radius:50%;
    width:150px;
    height:150px;
  }
  h2{
    font-weight:800;
    margin-bottom:5px;
  }
}

Any idea?

Upvotes: 1

Views: 2345

Answers (4)

Rakhat
Rakhat

Reputation: 4942

img tag by default is inline-block and you must use text-align: center in parent container to align img tag horizontally.
In case of it's display property value has been changed to block you should set styles margin-left: auto; margin-right: auto; to center horizontally.

Upvotes: 2

Kheema Pandey
Kheema Pandey

Reputation: 10275

As <img> tag is not a block level element which means text-align property will not work as expected. You can do 2 things to solve this issue.

  1. Either apply text-align: centeron parent element.
  2. make the <img> tag a block level element using display: inline-block;.

You can see a DEMO here.

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Setting display property for img would do the trick:

#profile-heading {
  text-align:center;
  margin-top:50px;
  img{
    border-radius:50%;
    width:150px;
    height:150px;
    display: inline-block; /* added this line */
  }
  h2{
    font-weight:800;
    margin-bottom:5px;
  }
}

Upvotes: 0

user1791914
user1791914

Reputation: 626

When I un-nested your styles everything worked in centering the image:

#profile-heading {
    text-align:center;
    margin-top:50px;
}
#profile-heading img {
    border-radius:50%;
    width:150px;
    height:150px;
}
#profile-heading h2 {
    font-weight:800;
    margin-bottom:5px;
}

Nested are only for CSS pre-processors using SASS or LESS.

Another way to center things is with auto left and right margins: margin: 0 auto; Hope this helps!

Upvotes: 0

Related Questions