Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to fix the position of some text so that it remains in place when the user scrolls. At the same time, I would like the text to be centered. When I use the code below, the text remains in place but it is not centered. How can I do both?

What I have tried:

<style>
   .heading {
     position: fixed;
     text-align: center;
    }
</style>

<body>
    <h1 class="heading">
     Hello
    </h1>
</body>
Posted
Updated 22-Aug-21 22:20pm

1 solution

Adding position:fixed takes the element out of the document flow. It will no longer stretch to the full width of the parent element. Assuming you want the text centred horizontally, you need to add width:100% to the style.
CSS
.heading {
    position: fixed;
    text-align: center;
    width: 100%;
}

NB: Any following content will be displayed underneath the fixed element. You may want to try position:sticky instead.
CSS
.heading {
    position: sticky;
    top: 0;
    text-align: center;
}
position - CSS: Cascading Style Sheets | MDN[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900