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,422
  • 5
  • 28
  • 41
Tech Sourav
  • 124
  • 1
  • 7

3 Answers3

3

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
  • 35,836
  • 15
  • 89
  • 111
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>
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0

.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>
CodeBug
  • 1,649
  • 1
  • 8
  • 23
Agile
  • 1
  • thankful for advanced full with a examples nice ! – Agile Mar 15 '23 at 06:14
  • hi @agile, welcome to SO, always add comments, notes, or descriptions to your answer, only a snippet may solve the problem, but a description gives more knowledge, read here more about how to answer https://stackoverflow.com/help/how-to-answer – CodeBug Mar 21 '23 at 04:49