Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I need to grab width of h2 with width: fit-content and based on that add before and after 10% left and right. It should be some decorative lines before and after text, but text length varies, so that’s why I have fit-content and trying to add margin on it.

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can try like below:

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>

Another version with one pseudo element:

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading