How to leave the background of a text the size of the text and not the paragraph?

Asked

Viewed 570 times

5

How do I make for the background-color of h4 be only the width of the text. I can’t delimit a fixed width because I don’t know the size of the text and I can’t use display:inline-block why need the H4 under each other. Does anyone know how I can do this or any other solution to the case will be welcome!

h1{
  background-color: yellow;
}
<h1>Testando!</h1>

What I’ve achieved so far is not the expected result:

inserir a descrição da imagem aqui

  • the headline tags H1, H2, etc occupy the whole line, so the behavior is right. To have a background only in the text you need to use another element, for example by the text in one label or span

1 answer

4


If your H4 is inside a container you can use flexbox to achieve its goal.

First you determine that in your container items will line up like columns, one underneath the other flex-direction: column; after which they will stay left to prevent them from occupying the entire line align-items: flex-start;

.container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
h1{
  background-color: yellow;
}
<div class="container">
  <h1>Testando!</h1>
  <h1>Lorem ipsum dolor sit.</h1>
  <h1>Lorem ipsum dolor sit. Lorem, ipsum.</h1>
</div>

  • Blza Hugo, I’m using Vue and the Vuetify which is a kind of Vue’s Bootstrap, so it already comes with the grid system that uses its own flex. I was a bit on the back foot to apply flexbox, but I think it will have to be anyway. Thanks for the reply.

  • @Leandrade A young man, if you are using BS4 the whole grid of it is already in flex, and it has native flex classes as you can see here: https://getbootstrap.com/docs/4.0/utilities/flex/ has pq not use flex in this case! Success there!

  • No, not Hugo. I’m using Vuetify which is a specific CSS framework for Vue.js, tbm has a grid system with flex classes. It has nothing to do with Bootstrap no.

  • 1

    @Leandrade ah ok, I traveled here rss, however it is part of the framework :)

Browser other questions tagged

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