Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading