Αννα Νου.
Αννα Νου.

Reputation: 61

Position Absolute doesn't center block

I want my block to be at the center of the page, but after I set position: absolute, margin-left and margin-right, auto doesn't work.

.block1 {
  position:absolute;
  bottom:0;
  height: 336px;
  width: 1020px;
  margin-left: auto;
  margin-right: auto;
} 

Is it possible to have position :absolute and center the block at the same time?

Upvotes: 1

Views: 150

Answers (3)

user663031
user663031

Reputation:

The classic way:

.block1 {
  position: absolute;
  bottom: 0;
  height: 336px;
  width: 500px;
  left: 50%;
  transform: translateX(-50%);
  background: purple;
} 
<div class="block1"><div>

Upvotes: 0

Steve K
Steve K

Reputation: 9055

You're on the right track. Just set the left and right on this div to 0 like so:

.block1 {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
  height: 336px;
  width: 1020px;
  margin-left: auto;
  margin-right: auto;
} 

Upvotes: 1

Niyoko
Niyoko

Reputation: 7662

Yes, if you have fixed width, use, left: 50% and margin-left: -halfWidth.

.parent-block {
  position: relative;
  height: 200px;
  width: 100%;
  border: blue dotted 1px;
}

.block1 {
  position:absolute;
  bottom:0;
  left: 50%;
  height: 100px;
  width: 150px;
  margin-left: -75px;
  background: red;
} 
<div class="parent-block">
  <div class="block1"></div>
</div>

Upvotes: 2

Related Questions