【问题标题】:Get what x% of an element is获取元素的 x%
【发布时间】:2022-02-11 21:08:06
【问题描述】:

我正在尝试将 HTML 元素的边距设置为其大小的 x%。尝试使用 margin-bottom: 50%margin-bottom: 50vm,但它得到了屏幕尺寸的 x%

代码:

#task_box {
  margin-bottom: 1%;
  display: block;
}
<input type="text" id="task_box">
<input type="text" id="task_box">
<input type="text" id="task_box">

我想将此设置为 task_box 对象。

【问题讨论】:

  • id 应该是唯一的!
  • 根据the MDN documentation,指定为百分比的边距相对于包含块的宽度
  • 我觉得,你得用js
  • @RichardDeeming 实际上是“相对于包含块的宽度的边距大小,以百分比表示。”
  • 你能用代码告诉我答案吗?

标签: javascript html css


【解决方案1】:

我认为唯一的方法是使用 JS。

const taskBoxes = document.querySelectorAll(".task_box");


taskBoxes.forEach(taskBox => {
  var height = taskBox.offsetHeight;
  var marginBottom = height / 2;
  taskBox.style.marginBottom = marginBottom + 'px';
});
.task_box {
  display: block;
}
<input type="text" class="task_box">
<input type="text" class="task_box">
<input type="text" class="task_box">

【讨论】:

    【解决方案2】:

    有助于解决问题

    .task_box {
      margin-bottom: calc(100% - 50%);
      display: block;
    }
    <input type="text" class="task_box">
    <input type="text" class="task_box">
    <input type="text" class="task_box">

    【讨论】:

    • 它占据了 100% - 50% 的屏幕。我希望它从 task_box 中获取大小
    • 好吧,你应该使用javascript。
    猜你喜欢
    • 2023-03-08
    • 2016-03-18
    • 2012-05-13
    • 2016-08-17
    • 1970-01-01
    • 2022-08-02
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多