【问题标题】:HTML - How to include padding/margin of the parent element in width percentage of current element?HTML - 如何在当前元素的宽度百分比中包含父元素的填充/边距?
【发布时间】:2019-03-06 19:36:44
【问题描述】:

我正在渲染我的组织的层次结构,它有两列:名称和人员。因为每个层次结构元素可以属于不同的层次结构级别,所以我使用 margin-left css 属性来区分它们。但是当我将 Name div 的宽度设置为 80%,将 People div 的宽度设置为 20% 时,每个级别的宽度似乎都不同,因为它们不包含父元素的 margin 属性:

目前我的 HTML 结构如下所示:

应用的 CSS 样式如下:

.item-name, .item-count {
    word-break: break-all;
    line-height:22pt;
    font-size:10pt;
    border: solid 1px grey;
    padding: 4px;
    display: inline-block;
}
.item-name {
    width:80%;
}
.item-count {
    text-align:center;
    width:20%;
}

我应该怎么做才能使 width:80% 和 width:20% 包括父 div 的边距宽度,无论边距值是多少?

【问题讨论】:

  • 寻求调试帮助的问题(“为什么/如何使这段代码工作?”)必须包括所需的行为、特定的问题或错误以及重现它所需的最短代码在问题本身。见:minimal reproducible example

标签: html css width margin


【解决方案1】:

我知道这不是最好的解决方案,但以下技巧对我有用(250px ~ 20%):

.item-count {
    text-align:center;
    width:250px;
}

然后每个带有 item-name 类的 div 都包含基于父级宽度和边距计算的宽度属性的内联样式:

<div class="item-row" style="margin-left:25px;">
    <div class="item-name id-2_2031" style="width:calc(80% + (25px * 0.8) - 25px)">
    </div>
    <div class="item-count">
    </div>
</div>

...

<div class="item-row" style="margin-left:50px;">
    <div class="item-name id-2_2031" style="width:calc(80% + (50px * 0.8) - 50px)">
    </div>
    <div class="item-count">
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 2012-05-09
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多