Ripol
Ripol

Reputation: 97

Centering a floated image in CSS

I have a javascript code and it needs to place images in different heights in a certein div according to the code. However, I also need the images to be centered. I searched the web and found different solutions such as using display:inline-block instead of float, but then the different heights don't work. Nothing I found seems to do the trick.

Here's the Javascript code that generates the final tags, margin_top is the variable that has the height difference needed.

var added_tags = ('<img style="margin-top:'+ margin_top.toString() +'px; float:left; margin-left:5px;" src="[Image source]" /> '+'<a></a>');

Upvotes: 0

Views: 74

Answers (2)

Johannes
Johannes

Reputation: 67778

You can't center floated elements. display: inline-block on the to-be-centered elements and text-align: center on their container is the way to go.

Concerning vertical alignment of different heights, you can use vertical-align: middle or top or bottom on the inline-block elements, whatever you need.

.wrap {
  text-align: center;
}

.wrap>img {
  display: inline-block;
  vertical-align: middle;
}
<div class="wrap">
  <img src="http://placehold.it/100x150/fa0">
  <img src="http://placehold.it/80x70/a0f">
  <img src="http://placehold.it/200x180/af0">
  <img src="http://placehold.it/50x120/f7a">
</div>

OR

.wrap {
  text-align: center;
}

.wrap>img {
  display: inline-block;
  vertical-align: top;
}
<div class="wrap">
  <img src="http://placehold.it/100x150/fa0">
  <img src="http://placehold.it/80x70/a0f">
  <img src="http://placehold.it/200x180/af0">
  <img src="http://placehold.it/50x120/f7a">
</div>

OR

.wrap {
  text-align: center;
}

.wrap>img {
  display: inline-block;
  vertical-align: bottom;
}
<div class="wrap">
  <img src="http://placehold.it/100x150/fa0">
  <img src="http://placehold.it/80x70/a0f">
  <img src="http://placehold.it/200x180/af0">
  <img src="http://placehold.it/50x120/f7a">
</div>

Upvotes: 1

Matt.C
Matt.C

Reputation: 1322

if you must use floated element the desired result can be acheived:

 section {
      padding:20px;
      margin:20px;
      border:1px solid silver; 
      box-sizing:border-box;
 }

 span {
      float:right;
 }

 section.centre span {
      margin-right:50%;
      transform:translateX(50%);
 }
 <section>
      <span>ALPHA</span>
      <br style="clear:both;" />
 </section>

 <section class="centre">
      <span>BRAVO</span>
      <br style="clear:both;" />
 </section>

Upvotes: 0

Related Questions