How to align the next lines of a <span> to the first line?

Asked

Viewed 44 times

0

I have a <div> which holds an image and a <span>, and my goal is that the image is aligned vertically to the <span> in the first line and the next lines of the <span> start at the same "left" position of the first line. To make it easier to understand, the end result should be this:

inserir a descrição da imagem aqui

Currently my code is this:

.row {
  width: 300px;
    display: flex;
    justify-content: space-between;
}

.row img {
    margin-right: 5px;
    vertical-align: middle;
}
<div class="row">
  <div>
    <img src="images/icon/image.png"/>
    <span>Esse daqui é o meu texto, e como podem perceber, a segunda e terceira linha não estão alinhadas com a primeira linha
    </span>
  </div>
</div>

As you can see, the next lines are not aligned. Analyzing the element in devtools, we can also see that the width of the element increases to cover the image. And probably, that’s the problem with the lines in the text not being aligned.

I also tried to use the element <p> passing a margin-left image size. In this case, the text is aligned as I want but it is not next to the image.

That said, how can I make the image stand next to a text in the first line and keep the horizontal alignment in the next lines?

  • You put Flex display on the Row, but it has to be on the div inside the Row, like. Row div { display: flex}

  • @hugocsl It didn’t make any difference. And I use in row because in some parts of my page, the content of row are 2 <span> that need to be left and right.

1 answer

2


Just put flex in div within the .row as I commented, and the result is as below. I didn’t touch your HTML that you posted in the question, I just put the CSS to look like you posted in the question image.

Edit about the author’s comment on the question: Use the flex property align-items: flex-start to prevent the image from stretch and be "stretched". The stretch is the default behavior of a flex container child, so you have to set in hand if you want to avoid this.

(if unable to use align-items: flex-start in the container, you can still put margin-bottom: auto; in img to avoid the stretch )

inserir a descrição da imagem aqui

.row {
  width: 300px;
    display: flex;
    justify-content: space-between;
}

.row img {
    margin-right: 5px;
    vertical-align: middle;
}
.row div {
    display: flex; /* div com flex dentro da row */
    align-items: flex-start; /* evita que a imagem sofra o stretch */
}
<div class="row">
  <div>
    <img src="https://via.placeholder.com/24x24.png"/>
    <span>Esse daqui é o meu texto, e como podem perceber, a segunda e terceira linha não estão alinhadas com a primeira linha
    </span>
  </div>
</div>

  • It worked, only now the image is distorted because it increased its height. How do I maintain the height that was before?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.