0

Here is a span that is sticky and I tried to place it exactly at the center of the document but I don't want to give margin-left or left because it does not give the exact center of the document.

So Is there any way to get an exact center with position sticky.?

.sticky {
  position: sticky;
  top: 0;
  background-color: yellow;
  font-size: 20px;
  left: 50%;
}
p{
  height:500px;
}
<h2>Sticky Element</h2>
<span class="sticky">I am from sticky</span>
<p>Some example text..</p>
Ganesa Vijayakumar
  • 2,216
  • 5
  • 23
  • 40
Tech Sourav
  • 124
  • 1
  • 6

2 Answers2

1

Use display: inline-block (?) and transform: translateX(-50%) to horizontal center your element.

.sticky {
  position: sticky;
  top: 0;
  background-color: yellow;
  font-size: 20px;
  left: 50%;
  display: inline-block;
  transform: translateX(-50%);
}
p {
  height:500px;
}
<h2>Sticky Element</h2>
<span class="sticky">I am from sticky</span>

<p>Some example text..</p>
Turnip
  • 34,740
  • 15
  • 87
  • 106
0

Try using display: table property:

.sticky {
    position: sticky; 
    top: 0;
    background-color: yellow;
    font-size: 20px;
    display: table;
    text-align: center;
    margin: auto;
}
<h2>Sticky Element</h2>
<span class="sticky">I am from sticky</span>

<p>Some example text..</p>
Akshita Karetiya
  • 1,235
  • 3
  • 11