Languages

CSS - make div element to be not larger than its contents

0 points
Asked by:
Ela-Davey
663

How can I make a div element to be not larger than its contents?

I would like the .parent element width be only as wide as the .child element.

My code:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
      background: orange;
    }
    
    .child {
      height: 100px;
      background: yellow;
    }

  </style>
</head>
<body>
  <div class="parent">
    <table class="child">
      <tr>
        <th>ID</th>
        <th>Username</th>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
      </tr>
    </table>
  </div>
</body>
</html>
1 answer
0 points
Answered by:
Ela-Davey
663

This effect is called "shrinkwrapping" and there are couple of ways to achieve it (display: inline, float, min/max-width). All of the solutions have different side effects.

In your case, I would use display: inline-block to make .parent width equal to the .child element.

Quick solution:

.parent {
    display: inline-block;
}

 

Practical example

In this section we present full working, runnable example of using display: inline-block property in HTML5 web page template.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
        background: orange;
        display: inline-block; /*   <----- required   */
    }
    
    .child {
        height: 100px;
        background: yellow;
    }

  </style>
</head>
<body>
  <div class="parent">
    Parent element text...
    <table class="child">
      <tr>
        <th>ID</th>
        <th>Username</th>
      </tr>
      <tr>
        <td>1</td>
        <td>Mark</td>
      </tr>
    </table>
  </div>
</body>
</html>

 

References

  1. display - CSS: Cascading Style Sheets | MDN
  2. float - CSS: Cascading Style Sheets | MDN
  3. min-width - CSS: Cascading Style Sheets | MDN
  4. max-width - CSS: Cascading Style Sheets | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join