DroidOS
DroidOS

Reputation: 8880

Responsive CSS transform for before pseudo-element

The effect I am after here is to show the word "Introducing" in the before pseudo element for an h1 header that has its own content centered. My effort thus far is shown below

h1::before
{
 font-size:0.7rem;
 content:'Introducing';
 position:absolute;
 left:calc(50% - 6em);
 top:-0.75em;
 transform:rotate(-45deg);   
  
}
h1
{
 text-align:center;
 position:relative;
 margin-top:30px;
}
<h1>
Hello
</h1>

This works and, as far as I can tell, is responsive - the before pseudo retains its placement relative to its parent. However, I suspect that this is not the right solution. Hopefully, someone here can suggest a better way.

Upvotes: 0

Views: 1919

Answers (1)

vals
vals

Reputation: 64164

Your current solution is responsive about different screen sizes, but it isn't about different h1 lengths. A longer text will need a different position.

You can solve it make the width of h1 adjust to its content. And now, just position the pseudo on the upper left, center it with a translation and rotate it.

h1::before {
  font-size: 0.7rem;
  content: 'Introducing';
  position: absolute;
  top: -1em;
  transform: translateX(-50%) rotate(-45deg);
}

h1 {
  text-align: center;
  position: relative;
  margin: 30px auto;
  width: fit-content;
  background-color: cadetblue;
}
<h1>
  Hello
</h1>
<h1>
  Hello World
</h1>

Upvotes: 1

Related Questions