如何定义一个宽度由子元素决定div(宽度自适应)?

//html
<body>
  
<div class="father">
  <div class="child">    
      <div></div>
  </div>

</body>

//css
  <style>
    
.father {
    width: 200px; height: 400px; border: 1px solid blue; 
    
    }

    .child {
        background: #ccc;
        height:100%;
        }
        .child>div {
            background: red;
            width: 400px; height: 200px;
        }
  </style>

我定义了个最外层,蓝色边框,包含一个子元素灰色盒子,灰色盒子中包含一个子元素红色盒子, 我想要的效果,是灰色盒子的宽度由子元素决定,而不是继承与父元素的。

在这里插入图片描述

这时只需要在child上添加 display: inline-block; 将最外层father的宽度去掉,也添加display: inline-block;

效果如下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/marendu/article/details/106790300
今日推荐