简体   繁体   中英

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?

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> 

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;
} 

The classic way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM