Help with centering absolute positioned item

Hello! I am trying to position the form in the first picture to the one in the second picture while keeping things responsive. transform: translateX(50%) works, but it is not responsive. Appreciate any help ^ Current Layout Code:
.hero {
position: relative;
}
.form{
@include m.mq(medium) {
bottom: 0;
width: min-content;
margin: auto;
position: absolute;
display: flex;
transform: translateY(50%);
}
.hero {
position: relative;
}
.form{
@include m.mq(medium) {
bottom: 0;
width: min-content;
margin: auto;
position: absolute;
display: flex;
transform: translateY(50%);
}
15 Replies
13eck
13eck12mo ago
To use position: absolute and transform: translate you need a few changes:
.element-to-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.element-to-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
That sets the top-left of the centered element to the mid-point of the parent container (with position: relative;) and then moves it left/up by half it's width/height.
omo
omo12mo ago
hey, thanks for the response! I have tried that before, and that centered the div in my hero section (it is positioned relative to the hero), while the one i want is centered at the bottom. Is there a way I could do that?
13eck
13eck12mo ago
I'm not sure what you're asking, sorry. Can you elaborate a bit?
omo
omo12mo ago
Sure thing ^ So if do this
.form
@include m.mq(small) {
position: absolute;
bottom: 0;
transform: translateX(50%) translateY(50%);
display: flex;
}
.form
@include m.mq(small) {
position: absolute;
bottom: 0;
transform: translateX(50%) translateY(50%);
display: flex;
}
omo
omo12mo ago
omo
omo12mo ago
it becomes exactly what i want, however
omo
omo12mo ago
omo
omo12mo ago
iit doesn't stay at the center u see so i'm trying to find a way to stick it there
13eck
13eck12mo ago
Are you resizing the window?
omo
omo12mo ago
yeah, but its the same in responsive mode
omo
omo12mo ago
13eck
13eck12mo ago
If you re-size the window it won't do a repaint on the absolute posititioned elements For that you'd need to do some flexbox or grid instead
omo
omo12mo ago
oh hm, so i hv to use grid to center it? there's no other way?
13eck
13eck12mo ago
If you want it to stay in the middle when the window is resized, yes Both grid and flexbox are dynamic so as the viewport changes so does the grid/flex container Absolute positioning is set once and done
omo
omo12mo ago
alright i got it, thanks for the help ^