How to Center in CSS
howtocenterincss.com
howtocenterincss.com
foo {
align: center;
valign: center;
}<table height=100% width=100%><td valign=center align=center>
And what the hell does "margin: auto" mean? I'd like to hear some print designers using that in normal conversation. "oh and also i'd like these margin's auto'ed".
At this rate the table tag is going live longer than the copyright on mickey mouse.
They look for the div with the most text/paragraphs in it and assume that's the article. At least, that's what the open source ones I looked at a while back do -- the proprietary ones that force you to go through their own server could use other tricks.
The stakes are much lower for Readability-esque algorithms, when they fuck up the user can just go back to the site's native presentation; screenreader users don't have that choice.
.. But then we've ended up with bootstrap and it's grid layout, where we're doing exactly that, and for some reason it's perfectly fine.
<div style="display:list-type; type-of-list:unordered"> <div style="display:list-item;">
?
What are you trying to say?
The phrase you were looking for is " I don't understand what you're saying."
Of course, the issue would probably come up rarely, since the browser stylesheets for those tags don't do anything particularly useful for anything other than lists and list items.
The primary problem with layout tables was that they involved tightly coupled inlining of your layout rules.
A failure of function availability from turning off images or CSS is a failure of developers, not a failure of the platform or user agent. You can find sites even in 2015 that either straight up work or degrade gracefully when being browsed by Lynx (a browser that I don't think has seen even a dot-release update since 1999) because they were put together by thoughtful professionals who understand the platform.
If you're trying to deliver an application that absolutely requires client side computation or specific browser APIs, you can have a pass for choosing the have your site not work without JS.
If your site really is just a series of documents (either static or dynamically computed), though, there really isn't much of an excuse.
In cases like this, wouldn't it make more sense to have that information available in an API? Once you've removed all styling and interaction, it seems like something that would work better as simply sending raw data, and letting the client decide what to do with it.
Schema.org is a good example of how this would work with the modern web. Markup relevant data (eg. product ratings, movie times) and let the clients render it as desired. You can still provide CSS/JS for modern browsers.
Seems a lot more elegant to me than designing pages to gracefully fallback when JS/CSS is missing, as that would seriously restrict design.
The crucial question is probably what's considered "raw" -- or perhaps to talk more in terms of web-related philosophy, which media type you'd expect most user agents to be able to handle by default... and despite the (reasonable) popularity of JSON, the answer is pretty much HTML with some kind of microformat information embedded via attributes.
In other words, the schema.org approach is arguably pretty much what you're supposed to do in order to design pages to gracefully fall back. I'm not sure why you might think those two concepts are at odds. :)
Honestly sure you need js for most interactions and animations still, but layout? I wouldn't merge any pr that uses js for layout. Including fully responsive layouts.
Seriously, I don't know what's more broken - CSS itself or the web developer community, with the amount of self-deception, cargo-culting and stockholm syndrome cases present there.
Grid based layouts are obviously useful but the table tag isn't the right tool.
Regardless of how you feel about CSS 2.1, it's indisputably better than the table-based layout we had before. Speaking as someone who has implemented both table-based layout and CSS 2.1, it's really unfortunate to see people want to return to the bad old world.
Completely disagree. The Unix philosophy is right when it comes to layout: you want to be simple, fast, and predictable.
This attitude is also why we are in a situation where the Web is slow compared to native platforms. Simple things tend to be fast things. Complex things tend to be slow things.
Your implications that table layout can be "well defined" or "heavily optimized" are both false. The problem is that table layout is ill-defined: it's really a pile of hacks upon hacks that were invented at Netscape a long time ago and still not standardized or consistent between browsers. And, speaking as someone who optimizes layout engines for a living, complexity is the #1 enemy of "heavy optimization". Spec complexity is the #1 reason why layout is so slow, because it makes layout engines large, complex, and brittle.
Not really. CSS grid systems (like in Bootstrap) require some ugly and non-semantic markup, but they're not very complex.
[0]: https://www.ostraining.com/blog/coding/bootstrap-right-way/
If you write your styles in the same preprocessor as the Bootstrap package you chose (Less by default, but optionally Sass), you can mix Bootstraps grid classes into your own semantically meaningful classes, and drop all the col-xs stuff from your markup. Your markup elements can have class names that are purely semenatic. Almost every modern grid system offers preprocessor mixins that can be used in this way.
There are methodologies like BEM that are great for providing a semantically meaningful layer of classes in your markup.
It's true that the complexity remains and is shifted. The important part is that it's no longer interlaced with the complexity that describes the fine-scale structure of the page.
There have been some huge deficiencies in CSS over the years. It is frustrating to have to use complex sets of counterintuitive rules to achieve seemingly simple effects. But there are techniques for helping to manage it in modern web development.
You can always increase complexity. For instance, by doing all math in Roman Numerals. Thus, in at least some cases you can decrease it. So your statement doesn't hold.
I think you were referring to something like inherent complexity, but then you would have to somehow prove that all this complexity is inherent.
Which is completely not like using CSS at all, right?
The whole web is fad-driven, so I'm glad at some point, pendulum will swing back.
Meanwhile, I'm just happy parallax fad is dying out.
This. And the confusion around those two goals is what drives a lot of useless arguments with people who have Stockholm syndrome towards HTML and CSS. Those arguments can often be summarized like this:
- Hey, we're complicating things too much, how about just focusing on rendering a text communicating a message?
- No no no, the web is not just about documents, it's so much more now! It's about applications.
- Ok then, so let's drop the nonsense about separation of concerns, that you can have layouts separate from content.
- No no no, HTML is for describing documents, and CSS is for describing its layout!
<table sortable >...</table>
Author email in straight text? Markdown is what you're writing already.
Author it in WYSYWIG/GUI clients? You only care about presentation.
It means "calculate the margins automatically according to available space". Nothing complicated about that.
Print is quite different from web. The most noticeable difference is that paper cannot be resized, nor does it adapt it's content when you rotate it.
position: absolute; top: 50%; left: 50%;
Is that so hard? Having poor CSS skills is not the same as CSS being broken.I'm not a fan of CSS due to issues like this. It falls in the same line as issues where, for example, paddings and margins (and borders) are added to the size of your div rather than subtracted. There's a solution for that that makes sense nowadays but by the time that came about, I'd already stopped liking CSS.
Vertical alignment is the real killer.
I think the secret is that maybe 10% of CSS writers actually have read more than the bare minimum to getting their layouts to work ( I am not among them, mind you).
foo {
display: flex; /* opt into the new box model */
justify-content: center; /* "align" */
align-items: center; /* "valign" */
}
Vendor prefixes may or may not ruin your day (for now), but the spec is there and is exactly what you want. CSS is no longer "badly broken" if that's your metric. @include background(linear-gradient(red, green) left repeat);
to autoprefixer: background: linear-gradient(red, green) left repeat;When you advocate an add-on to an existing solution, you're changing the solution. It's like people who recommend typescript in reply to JS's lack of types, or Coffeescript to its ugly syntax: you can't have both, they change the original thing. Or vimperator with firefox, or vim-mode emacs, or... it's all not the same thing anymore. You push the carpet down in one place, it comes up in another.
CSS still requires the vendor prefixes. If autoprefixer is the perfect solution to that, let's stop people everywhere from using vanilla CSS and switch them over to "CSS + autoprefixer". Turns out it's not that easy, which gives the original "but it requires prefixes" argument more meat.
[1]: http://dev.w3.org/csswg/css-multicol-1/#pagination-and-overf...
Probably the Prince song "1999" (party like it's 1999...) combined with the general era in which this stuff was figured out in non-web digital contexts.
The HTML email world is stuck with HTML 4.1, inline CSS and many corner cases (worse than the IE6 era!).
It might be for the better, actually. HTML5 and CSS3 are Turing-complete[0] so I can imagine that the moment they would be allowed, some clever marketing company would figure out new and impressive ways to use the new features to scam people. Er. I meant, "provide value-added content".
[0] - with user closing the loop, see http://beza1e1.tuxen.de/articles/accidentally_turing_complet... for links to an example.
You can do worse with less.
It doesn't belong on that page.
(Hint: basic arithmetic is turing complete if you give it the same affordances)
That said, I think it's important for people to understand that many of the problems that people have canonically associated with the web's incompetence have been "solved" in standards for a number of years. There's a real difference between problems that remain unsolved in all browsers and problems that do not remain in the current versions of all browsers.
That difference may seem moot until the features are universally rolled out, but understanding that a solution to centering content rolled out in all major browsers (including Internet Explorer) three years ago may help us get past a sense of learned helplessness about the web.
Yes, improving the platform takes time, but by making browser vendors aware of the problems we face as web developers, things do get better.
Nowadays people are not only using desktop computers. Many of the computer form factors used nowadays almost never update, yet one needs to support them.
EDIT: Typo version => browser.
foo<br>baz
renders correctly asfoo bar
but <span>foo</span><br><span>bar</span> renders as foobar.
And AFAICT it doesn't work at all in Safari even with vendor prefixes.
I still think there's scope for a language that compiles to CSS but allows totally intuitive positioning, provides error messages if you make a mistake and generally isn't as infuriating as CSS is. The amount of times I've done something which seemed like it really ought to do what I want and the layout doesn't change is unbelievable. Even assuming vertical alignment is totally solved by flexbox it's still an agonisingly painful thing to work with.
In QML I can center like this:
anchors.centerIn: parent
(replace parent with id of item you want to center in if not the parent item). You can also do just vertical or horizontal centering, or you can fill another item or you can anchor eg the left of your item the the right of another item and the right of your item someplace else and it resizes/repositions your item as required.Flexbox still often requires lots of nesting to achieve what should be (and is in QML) relatively simple layouts. I've also hit a few things that I couldn't do at all with Flexbox (although that could just be lack of CSS/flexbox skill on my part - but to that I say that CSS gets very hard quite fast, while complex layouts in QML are pretty easy).
Don't get me wrong, I'm glad CSS is getting better and will look forward to the day when I can use this (but lets be realistic, it'll be a while yet before enough browsers support this to be usable), but I can't help but feel that its cruft built on top of cruft and that it won't ever be as slick and simple as something like QML.
The fact that you say there is no easy vertical center, of which I disagree, doesn't make it broken. It means it's missing a feature you wish existed.
indeed, an extremely basic and fundamental feature than any site that implements popups could use.
That said, centering (and typography) in CSS and elsewhere is that you mix passionate people with a really hard problem and you don't get answers, you get a lot of debate. I used to read the alistapart mailing list and it was intense at times. Suffice it to say that when the content of part A and part B are different by 1 screen pixel, and you're centering, do you assume +1 pixel or -1 pixel? (You don't get 1/2 pixel resolution) a typically large debate
There's this misconception that CSS is a display language; it's actually designed as a typesetting language that must degrade nicely.
“The easiest way to vertically center something in CSS is to close your laptop and go to the bar.” - @jakeboxer
“How to choose between rem and em”
1. question css
2. question your life
3. throw away laptop
4. scamper into forest
https://twitter.com/iamdevloper/status/587651586350002176Browser support: http://caniuse.com/#feat=flexbox
http://dev.w3.org/csswg/css-grid/
Of course, it might be a while until there is broad browser support!
main.js:769 made it this far
main.js:1182 nope, not happenin today sir.
Leaving the sites broken in Safari (and maybe adding a notice that explains why it's broken) also helps keeping it at 4%.
It's more like Chrome is the new Internet Explorer, because lazy web developers decide to only target it, so we end up with sites specific to one web browser.
And like Microsoft, they are so damn slow to release updates and older machines don't even get any.
So: is it not degrading gracefully a property of the site, or a property of Flexbox?
I'm subscribed to a couple of constraint solver mailing lists. A common question is "why is my constraint solver doing this...?", or "how do I massage my constraints to achieve this...?"
With CSS You can't build a layout that 'fails' (in the sense that a solution cannot be computed due to improperly defined dependencies), and you certainly can't send your browser into an infinite loop by applying an incorrect style.
I still really like the idea of constraint based systems, but I think they are more suited to (web)applications rather than documents.
Which is what some people will tell you web is about when you point out to them they're doing something weird instead of writing a document communicating a message. Maybe it's time to separate those two use cases - web pages and web applications - because otherwise people will keep getting confused between the needs and problems of the two?
Anyway, GSS looks pretty cool.
For people that are use to hacks + grid systems, it seems weird at first, but over time you will become familiar with a rich layout system and stop thinking left-to-right, it will become more natural. The language of the spec and the declarations (align/justify distinctions, etc) can be weird at first, but you get used to it.
That's what 'layout' means after all, isn't it? Aligning one thing with another, to show they're related. I'm not a classically trained graphic designer, but doesn't any explication of visual fundamentals include 'alignment' somewhere up near its top?
Yet CSS really, really sucks at lining things up.
Anyone designing a better system might do well to start with the notion of alignment as a basic primitive/operator. To be able to say, item A here ought to line up with item B there (and if not possible, predictable behaviour C results).
My gut feeling is that one could then derive all other types of layouts from there. I admit that might be naive. Also, I realise that I've probably just described constraint-based layout, but as yet I haven't tested one of its implementations such as GSS in a real project.
If one were to consider these problems alone, CSS works quite well for what it was designed to do. Most designers I've discussed these problems with have problems more in their thinking than with the tool itself. They mostly try to apply print design thinking to web design, which simply does not work.
Example: <div class="item"><div><p>Your text here</p></div></div>
.item {display:table;} .item > div {display:table-cell;vertical-align:middle;}
I use this method on justindocanto.com to vertically center an unknown amount of text/elements inside a div that changes its size based on the size of the image that's inside it. Really nice technique when used correctly.
Wish there was another standard that could co-exist side by side on the web, something simple enough to be implemented reliably by the browser vendors.
That standard exists. It's called flexbox. It was designed to solve exactly this problem (among many others), and does.
That said, as I never tire of mentioning, vertical centering was a part of the design of CSS 2.1. The technique is called "absolute centering". See CSS 2.1 10.6.4 [1]: "If both 'margin-top' and 'margin-bottom' are 'auto', solve the equation under the extra constraint that the two margins get equal values."
[1]: http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-hei...
wtf?
do...do they know...how many manhours could've been saved...?
Personally, I don't find css to be that bad at all, but I work in it at least a little everyday so it might just be stockholm syndrome.
It is inefficient. It is awkward to set up in code, so many people write their own syntactic sugar around it. It crashes hard when it isn't 100% sure what to do with its constraints. Working with multi-line text is still a pain, so you often run into clipped text on iOS if you dare to increase the font size. etc.
A few years later and I don't think anything but the occasional third party api with undocumented behavior has been nearly as hard.
>Just use flexbox!
Which is great, except it isn't supported at all by IE8 or 9 and is only partially supported in IE10 (by prefix only). Which means a lot of people simply can't use it. I'm hesitant to use it myself, and I've got a very lax policy on supporting old IE.
I have run into a few IE10 gotchas, but they're all solvable. IE10 just uses an older version of the spec.
and IE itself will be cut loose from MSFT in a few months.
"A lot of people" = 4% on IE 8 & 9 (http://www.w3counter.com/globalstats.php)
1. margin: auto (wrong)
2. top: 50% (mostly wrong)
3. negative margin-top (correct if you know the size)
4. table-cell or translateY (correct)
5. a correct answer plus a discussion about why it has to be a hack
FWIW, when you set everything to "Unknown", this site tells you to use display: table-cell. If you don't have to support IE8, I generally prefer "top: 50%; translate-Y: -50%"[Edited for spacing.]
"margin: auto" seems to be the way that the designers of CSS 2.1 intended to center things. 90% of the time, absolute centering is the easiest way to center in CSS; you should prefer it when possible.
In my experience, most of the time when I do want to center something vertically, I have a defined height (which can be a percentage!), so absolute centering is the solution of choice.
Firefox uses pcwaltons method for images (resource://gre/res/TopLevelImageDocument.css). Do you want the image to be in the center/vertical of the div (with the div having a specified height)? If so, then pcwaltons method should work, as long as you have position:relative; on the div.
<HBox height="100%" width="100%" horizontalAlign="center" verticalAlign="middle">
<VBox>Col 1</VBox>
<VBox>Col 2</VBox>
<VBox>Col 3</VBox>
</HBox>The only approximation I could find was this:
.mydiv {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
This, however, looks horrible on most browsers as they either use hardware acceleration (resulting in blurry output) or they drop pixels (e.g. single-pixel lines) falling between the grid.I'm failing to understand your expectations.
Otherwise, if you don't need the darkening div behind the modal, you can easily create a centered modal with the container being the body tag. Without flexbox. Today.
Again, I don't understand your expectations.
Works for dynamically sized content (and statically sized content as well, obviously).
That will never stop being perplexing, no matter how many new models they throw on top to try to fix it.
Center a bunch boxes in a row and have overflowing boxes show up on the next row to the left or right. Doesn't work, it will center the next row as well.
I haven't found a non JS solution to this yet.
<div style="display:flex; align-items:center; justify-content:center; width:100%; height:100%">dynamic both v and h aligned center</div>
it's just sad to think that a browser can do so much stuff, yet it's unable to provide a good layout system.
Of course, when I actually implement it in my design, I prefer to separate my CSS from my HTML.
I wish the solution was presented in both flavors, side by side.
here is a sample (btw, it's so long ago now, I included modernizer.js and slectivizr.js but I have no idea if they were anything to do with this >_< and why I keep referencing "flexie" I have no idea, the script, if it even was a script isn't included on the page.... SO professional, such memory... ):
#box_content {
/* 1st draft flexbox required for IE8 layout using 'flexie' */
display: -moz-box; display:-webkit-box; display: -ms-box;
display: box;
-webkit-box-orient:horizontal; -moz-box-orient:horizontal; -ms-box-orient:horizontal;
box-orient: horizontal;
-webkit-box-align:center; -moz-box-align:center; -ms-box-align:center;
box-align:center;
-webkit-box-direction:normal; -moz-box-direction:normal; -ms-box-direction:normal;
box-direction:normal;
-webkit-box-pack:center; -moz-box-pack:center; -ms-box-pack:center;
box-pack:center;
/* 2013 flexbox! for FF3+, Safari3.2+, Chrome5+ */
display: flex;
display: -moz-flexbox; display: -webkit-flexbox; display: -ms-flexbox;
flex-flow: row wrap;
justify-content: space-around;
padding-bottom: 1.5em;
}
.phonebox, .addressbox, .qrbox, .emailbox {
max-width: 250px; min-width: 200px;
height: 165px;
display: block;
border-radius: 20px;
color: #4d4d4d;
box-shadow: 2px 2px 9px #333;
border: 1px solid #A2E86C;
margin-top: 0.5em;/* req. for small screens */
/* More flexbox for older browsers (flexie.js)*/
-webkit-box-flex:0; -moz-box-flex:0;
box-flex:0;
-webkit-box-ordinal-group:1; -moz-box-ordinal-group:1; -ms-box-ordinal-group:1;
box-ordinal-group:1;
}I want to just start using flex box everywhere, too, but we're just at the point where that's becoming realistic. I won't fault anyone for waiting if they have more representation from older browsers. The real progress lately has been the push for Microsoft to get IE onto more of an evergreen update schedule so we won't have to keep doing this once XP and IE8 are a bad memory.
By this, I mean generating the following individually: 1) the HTML with a class applied to a sample element to be centered 2) the separate CSS for that particular class selector
This is just a little nitpick based on my preference for avoiding inline styles; overall, nice work!
<center>Disrupt</center>The way absolute centering vertical alignment works in CSS makes sense once you understand containing blocks: you specify "position: absolute" to disable margin collapse and establish a containing block, you specify the offsets from the edges of the containing block that you want, and then you invoke the vertical-centering feature in CSS by saying "margin: auto".
I don't understand CSS all that well, but I do understand basic layout concepts and my specific intent, and it isn't very productive to have to wait around for people like you to write books and answer stack overflow questions just so I can use CSS to do what it was designed to do. If I write "margin: auto" on an absolutely positioned element, I would expect it to do nothing, since those are just contradictory demands. I wouldn't expect it to do something completely unrelated like vertical centering.
Adding "margin-collapse: disabled" would increase the complexity of CSS for no real reason, because now there would be three modes instead of two: static block, static-block-with-margin-collapse-disabled, and absolute position. There would be no benefit other than increased complexity of what is already a quite complex spec.
The real problem, IMHO, is that margin collapse exists at all. But that is not a CSS problem: that is a problem that goes way back to ancient, pre-CSS versions of HTML. A design goal of CSS, which was vital for its success, was to be backwards-compatible with HTML, in that you can describe every HTML layout in terms of CSS. (This is still not fully realized, because there are some bizarre corner cases involving things like <center>, which for example Hacker News relies on, but it's mostly there.)
I meant an explicit feature with it's own attribute.
I find it hard to fault the designers of CSS 2.1 for not being more complex than it was at the time. CSS 2 was a huge advance over CSS 1, so much so that a common feeling at the time was that CSS 2 had so many features no browser vendor would ever implement it all. The authors of CSS 2.1 had to maintain a delicate balance between giving authors the tools they needed and exploding the complexity of the spec, and making vertical alignment fall out of "margin: auto" was one of the ways they did just that.