【问题标题】:How to calculate width of the element and add margin based on its width如何计算元素的宽度并根据其宽度添加边距
【发布时间】:2022-02-15 05:24:50
【问题描述】:

我需要使用 width: fit-content 来获取 h2 的宽度,并在此基础上在左右 10% 之前和之后添加。应该是文字前后的一些装饰线,但文字长度会有所不同,所以这就是为什么我有适合内容并尝试在其上添加边距的原因。

.type-of-food {
        color: #fff;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        letter-spacing: 3px;
        margin-top: 100px;
        margin-bottom: 50px;
        position: relative;
        h2 {
            font-size: 1.5rem;
            height: 30px;
            width: fit-content;
            &::before {
                content: "";
                position: absolute;
                left: calc(width-of-h2 - 10%);
                top: 50%;
                width: 50px;
                height: 1px;
                background-color: white;
            }
            &::after {
                content: "";
                position: absolute;
                right: calc(width-of-h2 + 10%);
                top: 50%;
                width: 50px;
                height: 1px;
                background-color: white;
            }
        }
    }

【问题讨论】:

  • 所以你希望文本和行之间的间隙等于 h1 的 10%?
  • @TemaniAfif 是
  • 不完全确定它只能使用 CSS/SASS 来完成。 JS会是一种选择吗?

标签: html css sass


【解决方案1】:

您可以尝试如下:

h1 {
  width: fit-content;
  margin-inline: auto;
  position: relative;
}
h1:before,
h1:after {
  content: "";
  position: absolute;
  top: calc(50% - 2px);
  width: 10%; /* the space you want */
  height: 4px;
  box-shadow: 0 0 0 50px red; /* the width and color of line here */
}
h1:before {
  right: 100%;
  clip-path: inset(1px 1px 1px -100vmax);
}
h1:after {
  left: 100%;
  clip-path: inset(1px -100vmax 1px 1px);
}
<h1>text</h1>
<h1>Some text</h1>
<h1>more and more text</h1>

另一个带有一个伪元素的版本:

h1 {
  width: fit-content;
  margin-inline: auto;
  position: relative;
}
h1:before {
  content: "";
  position: absolute;
  inset: calc(50% - 2px) -10%; /* the 10% is your space */
  clip-path: inset(1px -100vmax);
  box-shadow: 0 0 0 50px red; /* the width and color of line here */
}
<h1>text</h1>
<h1>Some text</h1>
<h1>more and more text</h1>

【讨论】:

  • 这很完美!虽然我有错误 Incompatible units: 'vmax' and 'px'
  • @SlobodanDraksimovic 没有什么不兼容,你可以看到它运行良好。您可以改用大像素值,例如 -999px
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2015-12-16
  • 2012-07-24
  • 2020-02-15
  • 2013-09-10
相关资源
最近更新 更多