You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
The display: inline-block; force an element to generate a block box that's laid out as if it were an inline box. Let's try out the following example to see how this works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Expand DIV as Wide as its Contents using CSS</title>
<style>
.wrapper{
display: inline-block;
border: 25px solid black;
margin: 20px;
}
img{
border: 20px solid white;
}
</style>
</head>
<body>
<div class="wrapper">
<img src="/examples/images/sky.jpg" width="300" alt="Cloudy Sky">
</div>
</body>
</html>
Use the CSS
displayPropertyYou can simply use the CSS
displayproperty with the valueinline-blockto make a<div>not larger than its contents (i.e. only expand to as wide as its contents).The
need an explanation for this answer? contact us directly to get an explanation for this answerdisplay: inline-block;force an element to generate a block box that's laid out as if it were an inline box. Let's try out the following example to see how this works: