DEV Community

Discussion on: Horizontal centering in CSS

Collapse
crinklesio profile image
Kevin Pennekamp Author

Assume you have a blog post, like here on dev.to where all the text is centered in an article. The article has given a max-width and the margin: 0 auto properties. We want to spice up the layout, by allow images to have a bigger width (e.g. 50px more on both sides). Because the parent is constrained to a maximum width, the children are too. To allow for the effect, you have to make the child elements forcefully ignore the parents width and still keep them centered in the layout (by default if the child ignores the parents width, it will overflow in the reading direction, so on the right side).

Hope this makes sense.

Collapse
alvaromontoro profile image
Alvaro Montoro

You can go around that issue by setting a relative position to 50%, then translating the content 50% (which in that case will be 50% of the size of the element and not the parent):

.exception {
  position: relative;
  left: 50%;
  transform: translate(-50%, 0);
}
Enter fullscreen mode Exit fullscreen mode

Here is an example: codepen.io/alvaromontoro/pen/mdWgKdx

Thread Thread
crinklesio profile image
Kevin Pennekamp Author • Edited

Aah ofcourse, you are right. That is another solution for the same problem. Thanks for it.

I did found one downside though. This method feels to me to make it more difficult to have it scale better for responsiveness in cases where the child elements are less than 100vw and more than the --gap. But it is a personal preference I think.