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


This Content is from Stack Overflow. Question asked by user17026360

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.


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>

This Question was asked in StackOverflow by user17026360 and Answered by confusedCoder It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?