现有代码以及效果如下图,使绿色元素宽度适应内容而非继承父元素。
<!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;
}