Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
How to Center in CSS (howtocenterincss.com)
135 points by vdfs on May 14, 2016 | hide | past | favorite | 39 comments


Can someone explain to me what is this for if selecting 4 x unknown in all questions leads to this?

<div style="margin-left:auto;margin-right:auto;"> (DIV) <div style="text-align:center;">Text Content</div> (TEXT)

If this is supposed to work, then by reduction, having more information about height/width is unnecessary for both browser and CSS programmer. Why not just always use those two forms?


What you've posted will only center a `<div>` with a known width (ie, for `margin: auto` to center a child element within its parent, the width of the child must also be specified).

Not sure if you're mistaken in your comment or there's a bug in the site. When I select all unknown dimensions and a block-level element, it gives me a flexbox output (the right answer, IMO).


Hm. I never get any flexbox output unless I tick "Vertically: top". Perhaps a bug then.


This website is needed.

The fact that this website is needed for such an extremely common use case is strong evidence that CSS is fundamentally broken.


<div style="display: flex; align-items: center;">Hello World</div>

This works in the latest versions of all browsers. If you need legacy IE support things may get tricky.


and blam, you blew your CSS framework XD


But this website should not be needed.

This is is fundamental design requirement, and the tools we have are barely up to the task.

Flexbox is a good start, but articles like this should be completely redundant.


+1. One reason why most front end engineers go not have good CSS skills. No amount of LESS or SASS will fix CSS.


To be technical, css isn't broken-- it's just for styling.

Using css for layout was a fundamentally bad idea, but it was the best hack around at the time. And now it's enshrined :/


Every time I need to center a div, I have to google how to do it. I really hope this site ranks above the fold... because i'm going to forget the URL, and in a few months i'm going to google the same stackoverflow answer I search for each time.


Upvote it and it will be in your list of saved stories.


There's a way to centre variable width block elements that doesn't depend on flexbox, which is:

    .centred {
        /* Make the element only as wide as it needs to be. */
        display: inline-block;
        /* Let us apply positioning. */
        position: relative;
        /* Move the left of the element to the middle of the container. */
        left: 50%;
        /* Translate backwards half the width of the block, thus centring it. */
        transform: translateX(-50%);
    }
It's a useful bit of CSS to have around.


I use a similar trick all the time, especially for vertically centering elements. Also, mine usually includes the various vendor prefixes for the browsers.


That reminds of Zed Shaw's angry CSS rant in https://youtu.be/_CEBG_s92P8?t=525 It's on the obnoxious side, and has a lot of foul language, but it's interesting.


With flexbox?


This is the real answer. If you haven't yet embraced Flexbox then do yourself a favor and get on board, it's awesome.


I'm in the midst of a (long, long overdue) redesign on the principle site I maintain, and just discovered flexbox. It's kind of jaw-dropping how much simpler it makes everything. Flexbox plus box-sizing: border-box allowed me to solve in about fifteen minutes layout problems that had previously taken me a few days and poking and Googling and cursing.


Yup! I made flexboxpatterns.com, which contains many examples related to centering. Flexbox + PostCSS for cross-browser support and you're good to go.


I have checked your work out, I like it. Go further.....there's a real opportunity for someone to build deep and wide Flexbox development tools, which just don't exist right now.


How about also including ie9 fallbacks?


Whoa! Nice job!


That's one of the results that is returned if you select a version of IE that supports flexbox.


Only if you ignore all audience on IE maybe


Flexbox is supported in IE11, but unsupported in IE10 and lower: http://stackoverflow.com/questions/18019450/css-flexbox-not-...

And since IE10 is EOL, it is fair to drop support for that.


I'm completely on board with ignoring IE at this point. Even Microsoft is through with it. With its declining market share and quickly expiring install base (Vista kicks the bucket next year, 7 in 2020) the benefit of mangling my codebase to support the dying browser just isn't worth the cost to me anymore.


I am in the enviable position of being able to say "Not using a modern browser, sorry, my site is not for you. Upgrade to a latest browser or leave."

That does make using Flexbox a whole lot easier.

Having said that, Bootstrap 4 has optional Flexbox.


Or just use tables like we did in the '90s...


Tables are meant for displaying tabular data, they are not meant to be an invisible frame or grid for page layouts but this is what they were often used for.

Tables fell out of favour because many people used nested table structures which were messy and inaccessible to people with screen readers. (Note that non-nested tables are not inaccesible to screen readers.)

I actually think a table-inspired layout approach for CSS would have been simpler to understand and to implement than the clumsy, messy CSS methods we currently have. Even Flexbox has an over-engineered (or over-complex) feel for some of its rules. Oh well, the benefit of hindsight...


The hilarious part is the memo "don't use tables" was so completely absorbed it became rare to see a table even being used for tabular data. A whole slew of CSS to achieve a table-like effect was fairly common to see.


Yay. We replaced one mess (table-based layouts) with another (CSS.)

Have you ever view-sourced the pages on this site? Many nested tables...


I use tables then add css styling to them.


Generate Code button not working? I am using Chrome on Ubuntu OS


Open the console window on chrome, it displays why it wont generate the code.

In my case, I didn't specify a value for H and V ALIGNMENT and I got "bundle.min.js:3 Uncaught Invariant Violation: No horizontal alignment"

Love this website nevertheless.


Yes.

    Error: No vertical alignment  bundle.min.js:3
It was easier with tables.


I can't help but wonder why the committee behind CSS took so long to come up with a reasonable way to center content that works in all cases.


Maybe because HTML/CSS was intended to lay out and style documents, not support complex application layouts?


When specifically was CSS explicitly and officially said to be for layout?

As I remember, it began as styling, and people started using it for layout, and that became the best practice, though not official. I don't recall the announcement that its design was for layout, but I wasn't keeping up on the news at that point.

And since CSS is officially said to be supporting layout, why aren't they thinking of all web use cases?

If CSS is not for layout of complex applications, what should one use in that case?


I would add some errors or indications of what's required before submitting.


Or some help text on what's required.

Or some inline validation?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: