when i use top:50% and left:50%
the box is not directly in center. of course when the box is very small, it appears to be centered. but when box is a bit big, it looks as if it's not centered.
how can i resolve this ?
Use the "inline-block" value of the display property to display the inner <div> as an inline element as well as a block. Set the text-align property on the outer <div> element to center the inner one. This property only works on inline elements.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
using translate
will perfectly achieve that. simply apply this
div.centered {
position: fixed; /* or absolute */
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
source
top
and left
correspond to the top-left corner of your box. What you're trying to do is have them correspond to the center. So if you set margin-top
and margin-left
to negative of one-half the height and width respectively, you'll get a centered box.
Example for a 300x200 box:
width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -100px;
Horizontal: Use a fixed width and
margin-left: auto;
margin-right: auto;
vertical: That's not that easy. You could use
display: table-cell
for the surrounding DIV and then give it a
vertical-align: middle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With