How to center a p element in the screen without a body or html element and create a black background


What I want to do is to use <p onclick='this.innerHTML++'>0</p> and make this code have a black background that covers the whole screen and center the text in it. I want it to not have a body element or an html element as I just want the <p> element.

I tried using box-shadows and the transform property in the style attribute.

<p onclick='this.innerHTML++' style='color: white; width: 100vw; height: 100vh; transform: translate(-50vw, -50vh); box-shadow: 50vw 50vh black;'>0</p>

That just displayed a quarter of the viewport a fourth of whiteness which meant the box-shadow wasn’t working. I found it added a margin, so I removed it. It still didn’t work. It centered the text though. I know how to do it with 2 elements, but I want to keep the code with only the <p> element.

This time I tried using the background property.

<p onclick='this.innerHTML++' style='color: white; width: 100vw; height: 100vh; background: black; text-align: center'>0</p>

This time the code did everything correctly except positioning the text vertically centered.

Is it possible to do this all in 1 element, center the text both horizontally and vertically, and display a black background that covers the whole screen?

>Solution :

To center content you can either use flex or grid:

  display: flex;
  justify-content: center;
  align-items: center;

or with grid, it’s just two lines:

    display: grid;
    place-content: center;

I created a snippet for you. I changed your <p> tag to a button, since this would be more semantic valid HTML. You can of course use any element you like.

button {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  display: grid;
  place-content: center;
  font-size: 3rem;
  color: #fff;
  background-color: rebeccapurple;
<button onclick="this.innerHTML++" type="button">0</button>

Leave a Reply Cancel reply