如何使一个div的背景颜色小于其内容?



我有这个代码与这个css属性。我想让这个灰色的方框比里面的文字小,怎么做呢?

.media-body {
background-color: gray;
}
<div class="media-body">
<h5>Lagoa Azul</h5>
<span class="texto-media-body">
Cras sit amet nibh libero, in gravida nulla. Nulla 
vel metus scelerisque ante sollicitudin.
</span>
</div>

背景色覆盖整个元素。虽然有background-size属性,但它只适用于背景图像

为了克服这个问题,可以为背景设置一个伪元素

.media-body {
position  : relative;         /* Make any child element will be positioned relative to this container */
border    : 1px solid black;
}
.media-body::before {
content          : '';       /* Set empty content                      */
position         : absolute; /* Position the pseudo-element absolutely */
height           : 90%;      /* Set height and width as desired        */
width            : 90%;
top              : 5%;       /* Set the offset as desired              */
left             : 5%;
z-index          : -1;       /* Send element to back                   */
background-color : gray;  
}
<div class="media-body">
<h5>Lagoa Azul</h5>
<span class="texto-media-body">
Cras sit amet nibh libero, in gravida nulla. Nulla 
vel metus scelerisque ante sollicitudin.
</span>
</div>

最新更新