【CSS】宽度适应内容

7 篇文章 0 订阅

现有代码以及效果如下图,使绿色元素宽度适应内容而非继承父元素。
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      height: 200px;
      margin: 10px;
      padding: 20px;
      border-radius: 20px;
      background-color: antiquewhite;
    }

    .box {
      display: flex;
      padding: 5px 10px;
      line-height: 30px;
      border-radius: 10px;
      background-color: aquamarine;
    }

    .box div {
      margin-left: 20px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="box">Vue<div>更多</div>
    </div>
    ...
  </div>
  <div class="container">
    <div class="box">React18<div>更多</div>
    </div>
    ...
  </div>
  <div class="container">
    <div class="box">react-router-dom<div>更多</div>
    </div>
    ...
  </div>
</body>

</html>

方法一:fit-content

给子元素设置width: fit-content,使其宽度自适应内容。

.box {
  display: flex;
  width: fit-content;
  padding: 5px 10px;
  line-height: 30px;
  border-radius: 10px;
  background-color: aquamarine;
}

方法二:父元素flex

父元素flex布局更改主轴方向

.container {
  display: flex;
  flex-direction: column;
  align-items: start;
  height: 200px;
  margin: 10px;
  padding: 20px;
  border-radius: 20px;
  background-color: antiquewhite;
}

在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值