1

Probably is a stupid question. I look for it on Google but honestly I don't know how search it.

Look at this example:

.container {
  border: 5px solid black;
}

.text {
  border: 1px solid red;
  margin: 5px;
}
<div class="container">
  <div class="text">text1</div>
  <div class="text">Long text long text long text</div>
  <div class="text">example</div>
</div>

Why the text containers are long as the parent container and not as long as the inside text? And how can I do to make the text container long as the text?

whitecircle
  • 237
  • 9
  • 34
  • Does this answer your question? [Where is the default size of a div element defined or calculated?](https://stackoverflow.com/questions/35010655/where-is-the-default-size-of-a-div-element-defined-or-calculated) – ATP Mar 17 '21 at 16:49
  • @ATP Sure, very interesting! But how can I solve? I would like to "append" an on click event on the text div and I don't want that it is applied on a bigger area than the text area.. – whitecircle Mar 17 '21 at 16:51

2 Answers2

1

Divs are block level elements by default and take up the full width of their parent. To alter that behavior, use flexbox on the container and items:

.container {
  border: 5px solid black;
  display: flex;
  flex-direction: column;
}

.text {
  border: 1px solid red;
  margin: 5px;
  align-self: flex-start;
}
<div class="container">
  <div class="text">text1</div>
  <div class="text">Long text long text long text</div>
  <div class="text">example</div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
0

It's because your div is a display: block element by default, so it fill the whole container width.

You could use display: table on your .text elements if you want to keep line break between elements, or display: inline-block if you want them on the same line

.container {
  border: 5px solid black;
}

.text {
  border: 1px solid red;
  margin: 5px;
  display: table;
}

.text.inline {
    display: inline-block;
}
<div class="container">
  <div class="text">text1</div>
  <div class="text">Long text using display table</div>
  <div class="text">example</div>
</div>

<div class="container">
  <div class="text inline">text1</div>
  <div class="text inline">Long text using display inline-block</div>
  <div class="text inline">example</div>
</div>
Pof
  • 829
  • 5
  • 20