Using CSS, how do I centre text at a certain point on the page?

Viewed 44

I have a page of fixed width. I don't want to change the width. I want to centre some text on the page so that it is at the centre of the entire page.

Say, if the page width is 4000px and the screen width is 1920px, using text-align: center; puts the text at the centre of the visible part, that is, centred at 960. I can force it using the page width, but I want to make it so that the text is at the centre of the full width, even when I change the width.

So, if the width is 6000px, I want the text centred at 3000px. If it is 1000px, I want the text centred at 500px. And all the while, the screen size remains the same.

In addition, how do I accomplish this for a container that contains text that should be justified, but the container itself should be centred.

A reproducible example as requested:

#mainhead {
    background-color: pink;
    font-size: 50px;
    font-weight: 1000;
    color: #e0f2f1;
    text-align: center;
}

The page width in this example is set to 4000px due to other stuff. But the heading is always centred at 960px from left, rather than 2000px from the left.

2 Answers

Create a parent div with width 100% and make that a flexbox. Then use justify-content: center; and align-items: center; It should not matter how wide your screen is. This will make sure the text is always centered.

You should use class instead of id in most cases when doing CSS.

.parent {
  width: 100%;
  height: 100vh;
  border: 2px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mainhead {
  font-size: 20px;
  color: red;
  border: 2px solid blue;
}
<div class = "parent"> 
  <p class="mainhead"> TEXT IS ALWAYS CENTERED </p>
</div>

no matter what the screen size is.it will always be centered.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

div {
  width: 100vw;
  display: flex;
  justify-content: center;
}
h1,div{
outline:1px solid red;
}
<div>
  <h1>I Am Always Centered</h1>
</div>

Related