Reputation: 37
i need some advice on how to properly center text and left or right position images within an 'a' tag.
the goal is to have button with: - left aligned image - text centered horizontally but left aligen if more lines of text - all elements should be centered vertically. - must work on most modern browsers (ex. IE below 9 does not matter) - only using CSS
i made an exampel which seems to work with static heights (ex. 100px) here's my Fiddle: https://jsfiddle.net/CtH9k/5819/
--
but how does i make this work properly width dynamic heights, especially the text is giving my problems.
line-height: 100%;
here's my fiddle with dynamic heights https://jsfiddle.net/CtH9k/5820/
any good advices on what i may be doing wrong, perhaps some great tutorials or thoughts on this topic.
Upvotes: 0
Views: 67
Reputation: 9022
First, be carefull. When you use position:absolute
you have to add position:relative
to the parent you want to position your element with. In your first jsfiddle it looked like it's working because your a
, div
and body
are in the same position. In the second, your image gets "lost" because you added a span wrapper.
You can use this css:
top:50%;
transform: translateY(-50%);
With both absolute and relative position and you will always be sure that whatever the container or your element height it will always be centered.
so I added these properties to your current ones:
.spanText {
position:relative;
top:50%;
transform: translateY(-50%);
}
.imgWrapper{
top:50%;
transform: translateY(-50%);
}
a {position:relative;}
and it's working (try changing the "200px" height to whatever you wish:
Upvotes: 1
Reputation: 1266
Try flexbox.
a {
display: flex;
align-items: center;
}
a .textWrap {
flex: 1;
display: flex;
flex-flow: wrap;
justify-content: center;
}
<div>
<a href="#">
<img src="https://33.media.tumblr.com/avatar_11e745804f61_128.png" />
<span class="textWrap">
<span class="spanText">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</span>
</a>
<a href="#">
<img src="https://33.media.tumblr.com/avatar_11e745804f61_128.png" />
<span class="textWrap">
<span class="spanText">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</span>
</a>
</div>
Upvotes: 0
Reputation: 3429
you can try this one:
<div>
<a href="#">
<span class="imgWrapper">
<img src="https://33.media.tumblr.com/avatar_11e745804f61_128.png" /></span>
<span class="spanText">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</a>
</div>
Upvotes: 0