Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering div that is wider than its parent without setting negative left margin

Tags:

I have a div inside a div.

The div inside is wider than its parent so the normal procedure

margin-left: auto;
margin-right: auto;

produces an inner div where the left edge of the child aligns with the left edge of the parent.

When people answers this question, they uses to go for the negative left margin approach. Is there a cleaner solution?

like image 504
Anders Lindén Avatar asked Aug 19 '13 08:08

Anders Lindén


People also ask

How do I center a div without margin auto?

use text-align:center for div -> this will align text inside div center. include width property in div (i.e. width:200px) and it will work fine.

How do I center a div with margin?

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.

How do I center a div perfectly?

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 you center within a parent element?

Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.


2 Answers

You can use flexbox:

.outer {
  display: flex; /* Magic begins */
  justify-content: center; /* Center contents */
  width: 400px;
  height: 400px;
  background: beige;
  margin: 0 auto;
}
.inner {
  flex-shrink: 0; /* Don't shrink it even if it's too wide */
  width: 600px;
  height: 200px;
  background: pink;
}
<div class="outer">
  <div class="inner"></div>
</div>
like image 55
Oriol Avatar answered Sep 22 '22 11:09

Oriol


I worked out an easy way for absolute elements using a transform.

left: 50%;
transform: translateX(-50%);

Will center it if wider than parent.

like image 37
Jack Avatar answered Sep 21 '22 11:09

Jack