Issue
I'm trying to responsive center an absolute positioned div within another relative positioned div.
<div id="maindiv">
<div id="centeredDiv">
// ....
</div>
// ....
</div>
<style>
#centeredDiv {
position: absolute;
z-index: 100;
transform: translate(50%,100%);
}
</style>
I tried a lot of things but nothing is working on small screens. I need to responsive center the #centeredDiv div within the main div. I appreciate every suggestion.
Solution
You also need to position the absolute element on the x-axis and y-axis.
So you could give the centered element 50% from the left and 50% from the top.
To compensate this, you can use negative translateX and translateY of -50%.
body, html {margin: 0;}
#maindiv {
background: #ccc;
min-height: 100vh;
position: relative;
}
#centeredDiv {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background: #000;
color: #fff;
padding: 1rem;
}
<div id="maindiv">
<div id="centeredDiv">
center
</div>
</div>
Alternatively without giving offset values for left and right you could use flexbox, as such:
body, html {margin: 0;}
#maindiv {
background: #ccc;
min-height: 100vh;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
#centeredDiv {
position: absolute;
background: #000;
color: #fff;
padding: 1rem;
}
<div id="maindiv">
<div id="centeredDiv">
center
</div>
</div>
Answered By - prettyInPink
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.