Div not centering horizontally

I want to center a div horizontally and vertically. This is the CSS I’m using from

top: 50%;
    height: 50%;
    transform: translate(0, -50%);
    width: 60%;
    margin: auto;
    border: solid;

It is centering vertically, but not horizontally. It aligned left.

In what HTML element do you wish to accomplish this?

1 Like

The page.

What is this page?

Do you mean the body element?

1 Like

Yes, the body element. I’m trying to broaden my CSS knowledge. I just use left with width and top with height to position elements.

Showing the CSS alone gives us no context for where it is used. You need to also show the HTML you are working with.

1 Like

HTML

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>centered div</title>

<link rel="stylesheet" href="screen.css" media="screen">

</head>
<body>

 <div>
  <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec laoreet maximus lorem, vitae convallis tortor eleifend eget. Duis sapien tellus, blandit ac egestas eu, viverra vitae nunc. Morbi luctus maximus quam, vitae vehicula velit porttitor nec. Nunc consequat nunc et neque tempor, aliquet fermentum elit cursus. Suspendisse potenti. Sed sapien ex, ultrices nec suscipit in, volutpat finibus urna. Ut ut ex in libero molestie laoreet non quis nibh. Pellentesque at neque eget augue placerat semper. Pellentesque imperdiet odio eget gravida pulvinar. Nulla sit amet ipsum a justo volutpat laoreet. Vestibulum tempus iaculis mi vel ultrices. 
  </p>
 </div>

</body>
</html>

screen.css

html, body {
   height:100%;
   margin: 0;
 }
body {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f9f9f9;
    font: normal 1em / 1.5  arial, helvetica, sans-serif;
 }
div {
   width: 60%;
   padding: 0 1em;
   border: 1px solid #000;
   background-color: #fff;
 }

Example
https://codepen.io/Snady_Leiby/full/QWROjxR

Assume there is nothing else in the body element. Trying to center a picture frame on a wall, for lack of a better comparison.

<body>
<div class="className">

</div>
</body>

Here there is no content, so what do you expect to see?

An empty box centered horizontally and vertically. That’s it for starters. I will add content after.

From that article, to centre horizontally and vertically use:

.center {
  border: 5px solid;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
}

Better still use CSS Flexbox as in Post #7.

Thanks