我正在尝试创建一个宽度根据内部文本而变化的 div。
父 div 宽度为自动,子 div 宽度设置为 100%,即父 div 宽度的百分比。
但是父div占据了整个页面宽度。如何在动态更改文本长度的同时保持 div 的最小宽度以使整个文本位于一行中。
这里是实现
.filled-no-icons {
border-width:0px;
position:relative;
padding:0px;
width:auto;
height:auto;
min-width:91px;
min-height:36px;
background-color:rgba(0,0,0,0);
}
.filled-no-icons .rectangle-3 {
border-width:1px;
position:absolute;
padding:0px;
width:100%;
height:100%;
min-width:91px;
min-height:36px;
border-radius:4px 4px 4px 4px ;
background-color:rgba(0,150.0,136.0,255);
left:0%;
top:0%;
}
.filled-no-icons .content {
border-width:0px;
position:absolute;
padding:0px;
width:calc(100% - 32px);
height:17px;
min-width:59px;
min-height:17px;
background-color:rgba(0,0,0,0);
left:16px;
top:calc(50% - 8.5px);
}
.filled-no-icons .content .label {
border-width:1px;
position:absolute;
padding:0px;
width:calc(100% - 0px);
height:17px;
min-width:59px;
min-height:17px;
color:rgba(255,255,255,255);
font-family:Roboto-Medium;
font-size:14px;
font-weight:500;
letter-spacing:0.75px;
line-height:16.40625px;
left:0px;
top:calc(50% - 8.5px);
}
<!DOCTYPE html>
<html>
<head>
<title>
Button test
</title>
<meta charset="UTF-8">
</head>
<body>
<div class="filled-no-icons">
<div class="rectangle-3"></div>
<div class="content">
<div class="label">Button</div>
</div>
</div>
</body>
</html>
编辑: 添加 jsfiddle 链接
最佳答案
不完全确定为什么要将如此简单的设计变成复杂的 HTML/CSS。但通常您可以将容器设置为 display: inline-block
因为它具有 shrink-to-fit 功能。下面的示例没有任何标记更改。
不要将 .content
设置为绝对位置。就好像一个容器只包含绝对定位的元素,它会崩溃到什么都没有,只要你给它一些大小,但它不会知道里面的内容,这意味着盒子大小不能是动态的。
.filled-no-icons {
position: relative;
display: inline-block;
height: 36px;
line-height: 36px;
padding: 0 10px;
color: #fff;
}
.filled-no-icons .rectangle-3 {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border-radius: 4px;
background-color: rgba(0, 150, 136, 255);
}
.filled-no-icons .content {
position: relative; /* increase stacking order */
}
<div class="filled-no-icons">
<div class="rectangle-3"></div>
<div class="content">
<div class="label">Button</div>
</div>
</div>
<div class="filled-no-icons">
<div class="rectangle-3"></div>
<div class="content">
<div class="label">Lorem ipsum dolor sit amet</div>
</div>
</div>
关于html - 子div导致父div占满整个页面宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52666000/