Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: how to center box div element directly in center? [duplicate]

Tags:

css

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 ?

like image 871
aoghq Avatar asked Nov 12 '09 22:11

aoghq


People also ask

How can I center a div within another div duplicate?

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.

How do I center something in a div box?

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.

How do I center a box in a box CSS?

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.


3 Answers

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

like image 156
Biskrem Muhammad Avatar answered Oct 28 '22 07:10

Biskrem Muhammad


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;
like image 20
Amber Avatar answered Oct 28 '22 07:10

Amber


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
like image 5
Pekka Avatar answered Oct 28 '22 07:10

Pekka