将左填充和右填充设置为元素宽度的 10%



有没有办法在 Flexbox 中将左填充和右填充设置为元素宽度的 10%。 我尝试使用padding: 0 10%;,但它不是元素宽度的 10%。

.flex {
display: flex;
}
.item1 {
padding: 0 3px;
/*calculated depending on text width*/
}
.item2 {
padding: 0 16px;
/*calculated depending on text width*/
}
.item3 {
padding: 0 34px;
/*calculated depending on text width*/
}
/*can it be done with one rule for items*/
.item {
/*padding: 0 (width/10); something like this*/
}
<div class="flex">
<div class="item1">itm1</div>
<div class="item2">item2 with greater width</div>
<div class="item3">item3 with the greatest width ....................................</div>
</div>

编辑:我用javascript解决了它,但是可以在不使用js的情况下解决吗? 我只想将填充设置为文本宽度的某个百分比。

(() => {
const items = document.getElementsByClassName('item');
for (let item of items) {
item.style.padding = `0 ${item.offsetWidth / 10}px`;
}
})();
.flex {
display: flex;
}
.item {
border: 2px solid red;
white-space: nowrap;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="flex">
<div class="item">itm1</div>
<div class="item">item2 with greater width</div>
<div class="item">item3 with the greatest width ....................................</div>
</div>
</body>
</html>

这是一个只适用于Chrome的黑客想法。由于百分比填充将创建一个循环,因此使用动画将强制再次重新计算宽度:

.item {
display:table; /* OR inline-table if you want the element to be inline */
border:1px solid;
}
.item:before,
.item:after{
content:"";
display:table-cell;
padding:0 5%;
width:0;
animation:fix 5s linear infinite;
}
@keyframes fix {
to {
width:0.1px;
}
}
<div class="item">itm1</div>
<div class="item">item2 with greater width</div>
<div class="item">item3 with the greatest width ....................................</div>

了解与百分比填充相关的问题的相关问题:

CSS 网格 - 不必要的分词符

为什么百分比填充会破坏我的弹性项目?

因为在填充选项中使用 % 是指它的父宽度,所以假设如果您将弹性框宽度设置为 100px,在子div 中使用 30% 的填充将产生 30px 的填充。

这是一个简单的例子

.upper {
margin: 30px;
display: flex;
flex-direction: row;
width: 300px;
height: 80px;
border: 1px red solid;
padding: 5px;
/* this */
}
.upper>div {
flex: 1 1 auto;
border: 1px red solid;
text-align: center;
margin: 10px;
/* and that, will result in a 10px gap */
}
<div class="upper">
<div>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa<br/>aaa</div>
<div>aaa<br/>aaa<br/>aaa</div>
<div>aaa</div>
<div>aaa</div>
</div>

最新更新