Char
Char

Reputation: 318

Center a div and place it at the top of the page (CSS only!)

I've looked for this but can't find any good help. This is simple - I want to stick the div at the absolute top of the page and then have it centered. When I did position: fixed I also wrote top:0px and left:0px which then messed up the positioning. Help?

Upvotes: 0

Views: 42

Answers (2)

matthewpavkov
matthewpavkov

Reputation: 2928

You need to set a width and then set margin: auto so it centers horizontally.

.container {
  position: relative;
  background: #eee;
}
.positioned {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 50%;
  margin: auto;
  background: #ccc;
  text-align: center;
}
<div class="container">
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
  <div class="positioned">Content here</div>
</div>

Upvotes: 1

Florin Pop
Florin Pop

Reputation: 5135

Use position:fixed with top:0px - for the div to be in the top and with left:50% for the div to be in the middle.

Upvotes: 0

Related Questions