Hacker News new | past | comments | ask | show | jobs | submit login
How to Center in CSS (2015) (howtocenterincss.com)
161 points by HeinZawHtet on May 19, 2020 | hide | past | favorite | 69 comments



Centering in CSS is "solved" problem if your "worst" browser to support is IE11. Flexbox does the job there.

However, there are still couple of common tasks that are pain/hard/impossible to do with just CSS.

Recently I learned that after all this years you still need to use JS to get css animation for dynamic height ("height:auto") of elements.

And there is no progress in fixing it at CSS standard level. It's just sad... https://github.com/w3c/csswg-drafts/issues/626 https://stackoverflow.com/questions/3508605/how-can-i-transi... https://stackoverflow.com/questions/3508605/how-can-i-transi...


There are some tricks you can use if you know the max possible height your element can have, but it's not great, yeah.

Edit: Oh, I just saw that the stackoverflow question you linked has this for the accepted answer :)


The problem is the animation speed is overly fast if you're at less than that maximum height.


12 years ago at W3C styles I've proposed to solve it as simple as this:

   .in-the-middle {
     width:max-content;  
     height:auto;
     margin:*; // "coils" on all sides moving it 
               // to the middle of free space in container
   }
So these tons of tools, essays and doctoral dissertations on "how to center stuff" would not be needed.

Here is the story: https://terrainformatica.com/2018/12/11/10-years-of-flexboxi...


Pinboard tells me, I "previously saved april 2015". So I bookmarked this more than five years ago.

Back then, this site was addressing a big problem and, to some degree, it's still a confounding problem sometimes.

So high-five to its creator. And to the HN haterz in these comments, take a hike.


Saw the link was already clicked and was curious. I've still got this page bookmarked in chrome from when I was first starting out as a web developer.


This is a straw man.

Today you can simply use flexbox on the container:

  display: flex;
  justify-content: center; // horizontal
  align-items: center; // vertical
Doesn't work in IE without a JS polyfill (which is available), but has worked in all other browsers for six years or so.


That is exactly the code the website will generate if you select no IE support.


Actually it also works in IE11, as it should. Flex does work in IE11 with some known bugs - https://caniuse.com/#search=display%20flex


Yet it opens with this misleading blurb:

> Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors.

Which is no longer true in the great majority of cases.


That's only misleading if you don't have to support IE. I'm guessing that's the case for you but many of us still have to.

Also, this site seems to have gone up in 2015 and hasn't changed (substantially) since.

I also don't think you're correct in calling this a straw man. This is not a debate and there was no other party whose assertion this site seems to refute, so calling it a straw man doesn't seem to fit.


Well it's not true if you decide to ignore the fact that this does address the situations in which centering is a pain in the ass. If you exclude all the factors this takes into account, it obviously becomes trivial.


It is always the minority of cars that kill you. If it only has to 95% work, that’s always been easy.


Flexbox (and grid) have made frontend work tolerable again for me. You can do in a handful of lines what used to take all kinds of jiggerypokery, hacks and extra markup to wrap things.


For me as well, specially grid, since it was originally submitted by XAML team and is heavily influenced by its grid layout engine.


What does a JS polyfill have to do with CSS? Also, try that out in IE 11 without a polyfill.

This works in IE without a JavaScript polyfill (lol): <html> <body> <div style="width: 400px; height: 400px; background: red; display: flex; align-items: center; justify-content: center;"> <div>TESTING</div> </div> </body> </html>


And yet six years later still no widespread support for the 'safe' keyword. Which means the content can overflow the container without a way to scroll to some parts of it: https://jsfiddle.net/r50qseah/


What is the 'safe' keyword?



Yes, with flex we don't need anything else. If flex is not available, the browser is supposedly too old to care if we used tables for layout so I'll just throw in `display: table-cell`.


that can cause some issues in Chrome oddly enough, depending on how you're using it.


A wise man once said (me): ill use <center> until the end of time and thy browsers shall support it. (did of course learn the new and improved ways to qualify the ignorance)


Google’s home page uses it three times.


HN wraps the whole page in a centre tag.


Having to still support IE 11 for most projects, I really like the following:

div { position: absolute; right: 50%; bottom: 50% transform: translate(50%, 50%); }


IE11 supports most of flexbox. You don't need hacks.


forgot the <


It's time to learn flexbox


It's too bad flexbox isn't as easy to understand as box model; that puts the breaks on adoption, regardless of how well it handles the centering scenario.


Flexbox is far simpler than the box model.


Box Model is a living mess


Here's what I've been doing for years (The <div> can be any element, like <ul>):

<div id="wrapper" style="text-align:center"> <div id="wrapped" style="display:table;margin-left:auto;margin-right:auto;text-align:left"></div> </div>

WFM YMMV


You don't need the style="text-align:center" on your wrapper element


> You don't need the style="text-align:center" on your wrapper element

Why not? The goal is to center something with an unpredictable size.

display:block adapts to the container. display:table adapts to the contents.

This uses both.


A box isn't text. Why don't you give it a whirl.


Oh, I see. Gotcha. I use it for images and lists, so I've gotten used to it.

Cool. Thanks!


you really use the same id twice on a page?! Heresey! Also.. I do the same (essentially: margin: 0 auto) but it works with display: block too, and you don't need text-align center on the parent.


It's not the same id: wrapper vs wrapped


They were not IDs. They were indicators of what the div is for.

It was sort of HTML-pseudocode.

In any case, this is exactly how you center something that doesn't try to stretch across the entire page. It's old-fashioned, but robust.

Also, I would generally not use inline CSS. I think of it like I think of !important: the nuclear option.

That said, I tend to use inline styles a lot for WordPress site content, because I don't want to deal with the slow-ass "customize" option.


    <div class=element></div>
    
    <style>
    .element{
    position:absolute;
    width:500px;
    height:500px;
    left:50%;
    top:50%;
    margin-top:-250px;
    margin-left:-250px;
    }
    </style>


Don't do this, you will run into edgecases that make things look jank. Use flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/


Thanks for the tip. Any particular browser that causes such 'jank'?


This would center a fixed sized element in absolute position to page, this was never an issue. Problems start when you do not know size of your element and its parent. Flex finally fixes[1] this issue but it was not fully supported until recently[2].

[1] https://philipwalton.github.io/solved-by-flexbox/demos/verti... [2] https://github.com/philipwalton/flexbugs

Most of the flexbugs are now fixed and flex should be recommended way of making layouts.


This requires advanced knowledge of the width and height of the `.element`


I was explaining this to a normal person the other day, and maybe I'm doing it wrong, but it was impossible not to make it sound like we are weanies. I mean complete knee-biting berks.

"What do you mean centering was hard?"

"Not was, still is."

"..."

"yeah. ..."


It doesn't solve vertical centering, but I am secretly still a fan of the center-tag. Just does what it's name implies in most situations. I still don't get why its avoided like the plague.


Earlier HTML had tags that styled elements. The community decided it would be better if styling was left to CSS and HTML simply described document structure. This way styling lives in one kind of file instead of two different places.

I wouldn’t recommend using it for big or professional projects, but I guess it’s fine for personal stuff. Like the other comment said it’s an obsolete tag. Browsers tend try hard not to break old HTML but not sure that’s guaranteed to always be the case.


Didn’t HTML5 remove the <center> tag? In that case, just seeing the HTML5 DOCTYPE should allow ignoring those elements (as in not styling them). For example, if I do:

    <center>
        Text
    </center>
...just treat the tags as <doc> tags:

    <div>
        Text
    </div>
I understand there are many websites following older standards, but I can wish (for HTML5 to have been “strict”)


I know, but I still think <center>text</center> ist more readable then most of the css workarounds we had to use in the past.


There are to many websites using it to ever remove it.


It's avoided because it's obsolete and is not in the HTML5 spec: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...


I've been doing HTML for ~10 years and have never seen this before. Apparently, it was deprecated with HTML4 already, though I'm not sure why.


Probably the same reason that <b> (bold) and <i> (italics) aren't used anymore. There's now a clearer delineation between document structure (described via tags) and style (described via CSS) than there was in the earlier HTML specs.


b and i are back though, but a little different ;)

> The b element represents a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede.

and

> The i element represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, transliteration, a thought, or a ship name in Western texts.

[0]: https://html.spec.whatwg.org/#the-b-element

[1]: https://html.spec.whatwg.org/#the-i-element


To add to this: if you want to draw attention for reasons that don’t fit the <b> and <i> tag’s purpose, there’s <em>.


If you allow user generated input it is fine to allow <center>, <b> or <i>


Now I feel old. On the other hand, apparently I'm doing HTML for >20 years. Let me tell you about blink and marquee ... ;)


For some reasons, I've encountered those before. :)


Silly human! One does not simply center in CSS.


One which I came across recently, a little smaller than the usual flex solution:

.v-h-center { display: grid; place-content: center; }


I am not into the CSS game anymore, if anything needs to be done I'd just go with whatever widgets any CSS framework offers, but why has it been so hard for so long to center things with CSS (I believe flexbox finally fixed it) ?


Flexbox did fix it, and it's been available in Chrome since 2013, Firefox since 2014, and everything else since 2015. IE 11 supported enough of the 2012 syntax to be usable. Even IE 10 supports some of it, albeit poorly.


2015 ? Yeah, I think I remember hearing about flexbox around that time, also when I stopped doing any CSS work (which I had started around ~2000 I think).


I just throw a <center> in, it works well enough for most cases.


I prefer <center style="text-align: center;"> for maximum centeredness


<center class="center1 ct cen algn" id="center42" style="text-align: center; margin-left: auto; margin-right: auto;">


I love that


https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ce...

The <center> element is obsolete and is not in the HTML5 spec...


So? The browser doesn’t care.

You’re right of cause and centering is styling and it doesn’t belong in the html. It just that sometimes I really can’t be bothered with css and the center hr and a ton of br slips in, and it works well enough.




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

Search: