Reputation: 61
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
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
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
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