Home > front end >  Flexible way to vertically center top line of text box beside image
Flexible way to vertically center top line of text box beside image

Time:05-19

Seems quite easy, but I couldn't figure out the right css balance.

What I want, is this result(orange block is image):

enter image description here

This is easy, if the image has fixed height and text fixed properties (line-height etc.), but I need this to work, even if I insert it into different places on my website, it needs to automatically adjust to the size of image and text properties. So if image gets bigger, or text has different size / line-height, it still works. I might omit text variations, but different-sized images need to work.

So far, I only got display: flex with align-items: center, but that works only for one line, once it breaks to new line, it centers the whole text block, which is wrong. There's gotta be some css trick to achieve this, right?

EDIT: After another trial, I managed to come up with something better, but the text still needs to be controlled (top value of text must be: line-height / -2)

.txticon {max-width: 250px; display: block; margin-bottom: 15px; display: flex;}
.txticon::after {content: ""; clear: both; display: table;}
.txticon img {float: left; margin-right: 10px;}
.txticon span {line-height: 20px; top: -10px; position: relative; overflow: hidden; transform: translateY(50%);}
<a  href="#">
  <img  src="https://via.placeholder.com/100x100" alt="">
  <span>One line text</span>
</a>
<a  href="#">
  <img  src="https://via.placeholder.com/100x100" alt="">
  <span>Multiple line text which is really really really long</span>
</a>

CodePudding user response:

<div >
  <img />
  <p>Text</p>
</div>

.row {
  display: flex;
  align-items: center;
}

This might work.

CodePudding user response:

Would a margin-top on the text block work?

<div >
  <img />
  <p >Text</p>
</div>
.row {
  display: flex;
  align-items: flex-start;
}
.text {
  margin-top: 10px; // replace with half of the image height
}
  • Related