html - 将 padding-left 和 padding-right 设置为元素宽度的 10%

标签 html css flexbox

有没有办法在 Flexbox 中将 padding-left 和 padding-right 设置为元素宽度的 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 Grid - unnecessary word break

Why does percentage padding break my flex item?

关于html - 将 padding-left 和 padding-right 设置为元素宽度的 10%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102226/

相关文章:

html - Symfony 3 - 导航栏在除一页以外的每一页上都正确显示?

css - 图片不在轮播中居中

javascript - 突出显示所选菜单项不起作用

Chrome 的CSS字体系列问题

css - 使用 CSS 列 'page-break-inside' 不适用于 Flexbox 'align-items:center'

html - bootstrap 4列高度等于具有大可滚动内容的兄弟高度

css - 忽略 nowrap 的 Firefox 文本溢出(Chrome 有效)

javascript - 在下拉列表中显示保存的数据 - html select 标签

javascript - 如何防止单击电话号码时触发“onbeforeunload”?

php - iframe xss防护不同域