How do a div or span occupy only the size of its internal content?

Asked

Viewed 3,072 times

4

How can I make the div or span occupy only the space of its internal content? When I create a div here, it always takes up 100% of the space.

I tried this but it didn’t work:

 div{
    padding: 10px;
    color: #fff;
    font-family: "Roboto Condensed Bold";
    background: #82b6ea;
    width: auto;
    /* flexbox */
    display: -webkit-flex;
    display: flex;

    /* comportamento: em linha com wrap */
    -webkit-flex-flow: row wrap;
    flex-flow: row wrap;

    /* conteúdo justificado no centro */
    -webkit-justify-content: center;
    justify-content:center;
    -webkit-flex: 1 0 auto;
    flex: 1 0 auto;
    box-sizing: border-box;
}

3 answers

7

To div is a block type element and by default it occupies 100% of the container width. Span is a line element, and by default it only occupies its own size.

So in the case of div In case you wanted her to occupy only her own size you can leave her with display:inline-block, so it gets "hybridized" and gets characteristics of an element block and inline. Another option is to use min-content or max-content in the width of that div, here are more details What are and how the width values max-content and min-content work?

See the example below to better understand.

div,
span {
  border: 1px solid #000;
}
div.ib {
  display: inline-block;
}
div.min {
  width: min-content;
}
div.max {
  width: max-content;
}
<div>DIV padrão - Lorem ipsum.</div>
<div class="ib">DIV inline-block - Lorem ipsum.</div>
<div class="min">DIV min-content - Lorem ipsum.</div>
<div class="max">DIV max-content - Lorem ipsum.</div>
<span>SPAN - Lorem ipsum.</span>


Another detail

An element, same as block, when with position:absolute, or fixed also takes up only the size of the element itself, as it changes its scope in the content stream of the page. The same happens when using float:right or left in div.

div.pos {
  border: 1px solid #000;
  position: absolute;
}
div.float {
  border: 1px solid #000;
  float: left;
  margin-top: 30px;
}
<div class="pos">DIV position:absolute - Lorem ipsum.</div>
<div class="float">DIV float - Lorem ipsum.</div>

1

At first just put display: flex in div with width: max-content or min-content that will work.

Example:

  • HTML
<div class='myDiv'>Conteudo</div>
  • CSS
.myDiv {
  display: flex;
  width: max-content;
}

Tip: Research a little more on flex-box, will help you a lot in these things.

1

If I understand correctly you must want to use css display with the value table or inline-table

.teste1{ 
    display:table;
    border: 1px solid red;
    margin-bottom:4px;
}
.teste2{
    display:inline-table;
    border:1px solid blue;
}
<div class='teste1'>Meu texto</div>
<div class='teste2'>Meu</div>
<div class='teste2'>texto</div>

Display - Maujor

Browser other questions tagged

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