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

时间:2019-11-29 09:37:25

标签: 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>

3 个答案:

答案 0 :(得分:1)

这是一个骇人听闻的主意,仅在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?

答案 1 :(得分:0)

由于在填充选项中使用%表示其父宽度,因此,如果将flex box width设置为100px,则在子div中填充30%的填充将使30px填充。

答案 2 :(得分:-1)

这是一个简单的例子

.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>