如何计算元素的宽度并根据其宽度添加边距

How to calculate width of the element and add margin based on its width

我需要用 width: fit-content 抓取 h2 的宽度,并在此基础上添加左右 10% 前后。文字前后应该是一些装饰线,但是文字长度不同,所以我有fit-content并试图在上面添加边距。

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