Tech Sourav
Tech Sourav

Reputation: 134

Achieve position sticky content at exact center?

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>

Upvotes: 0

Views: 2917

Answers (3)

Agile
Agile

Reputation: 1

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

Upvotes: 0

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

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>

Upvotes: 0

Turnip
Turnip

Reputation: 36712

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>

Upvotes: 3

Related Questions