Aligning Text Smartly in CSS

Have you ever thought of aligning text smartly in CSS? You must try now.

No there is no CSS property text-align:smart or smartly

Let’s see an example

smart-text-alignment

Here we are trying to achieve text-align: left when the text is more than one line in the given container.

This is very simple to achieve.

Now we want to make the same text align center if its well fitted in a single line.

Here’s what we can do by pure css without using javascript

Codepen Demo: Aligning Text Smartly in CSS

How it works?

This not only works with figure and figcaption. It works very well with any nested element like a <p> within a <div>.

When we are setting the parent container to text-align: center, we are saying the parent container to make all inline elements to align horizontally center.

So all child inline elements will obey the rule including inline-blocks as well. In the above example we have set figcaption as inline-block. This is what makes it align centered.

As we know that inline-block elements grow wider max till 100%(considering padding and no width defined) of its parent based on its content. When the content text of figcaption is less, it’s aligned center by virtue of the property text-align:center defined on its parent figure. Check this post to know more about inline-block elements behavior

As the text of figcaption grows into multiple lines, it keeps widening to the max width of its parent figure width. Now the magic starts! text-align: left; defined on figcaption makes the content text left aligned.

In reality, figcaption is always aligned center but its not obvious as it has attained the max width of its parent.

Hope you have enjoyed this article, and follow me on twitter @sharmavijay for all the awesome blogs.

Visit www.nocode.in for more interesting posts.

  • I think I found an even simpler version with no CSS on the figcaption. Using flexbox.

    http://codepen.io/MoOx/pen/XdVjpK

    • Nope

      And doesn’t work in the majority of browsers.

      • According to caniuse database, as I am writing this, flexbox is supported by 95% of browsers.

        http://caniuse.com/#search=flexbox

        Only IE 9 and 8 do not support it. Please consider this things:
        – companies like Facebook and Google dropped support for IE 8, so you should be able to do the same
        – IE 9 have auto updates by default, so most users (except the one that disabled auto update on purpose) will have IE 11 (since IE 10 is also auto updated).

        Except if you work for a internal project for a company that have blocked their Windows updates, normal users have IE 11 this days. So flexbox is totally ok.

        • eterterewwerwr

          IE9 is not an evergreen browser. IE9 is the last IE version in XP and Vista. Users can’t update to IE10 from these systems. Please check your facts.

          • CoryRs

            There’s hardly anybody still using Vista, and the XP marketshare is always decreasing. Of these users still on those versions of Windows, not all of them use IE. Also, Windows XP can only get IE 8, so I think YOU should be the one checking your own facts, buddy.

          • Redditor111111

            IE9 does not autoupdate on XP and Vista, that is a fact. I don’t see anything wrong with his comment. If you can ignore those 5℅ percent than that’s fine, but not everybody can.

          • CoryRs

            What part of “XP can’t get IE 9” do you not understand?

          • guest

            What part of “IE9 doesn’t not update automatically” do you not get?

          • name

            What part of “IE9 does not autoupdate on XP” seems weird?

            We can also say “Edge does not autoupdate on XP”

          • CoryRs

            You’re an idiot.

          • CoryRs

            Really? Explain to me exactly where it looked like I didn’t understand that. Then, also realize that just because it’s the browser that came with their computer, doesn’t mean people have to use it.

          • If people are still using Windows XP and at the same time they are also using IE they have far bigger problems to deal with than seeing your website.

          • Patrik Jarl

            Hear hear.
            About 11-16% of users worldwide still use XP. (how many of these using IE9 I don’t know). Primarily in development countries but still, it’s quite a lot of users. If you’re producing sites for worldwide users this group can’t be ignored.

            Always focus on your user group and choose technique depending on that.

            https://redmondmag.com/articles/2015/04/08/windows-xp-usage.aspx

          • kitsunde

            Support for Windows XP ended April 8, 2014. You’re doing something very wrong if you support anything on that OS.

        • MongooseDoom

          I think the important thing here is that you always consider your users first. If your users don’t use IE9, go ahead with flexbox! If you have a large amount that do, you’ll want to find a different solution.

        • lkt

          I have to admit I don’t understand why people still argue over browser support. The whole thing is very simple:

          – Some people NEED to support older browsers. Maybe their visitors are older, maybe they live in a different country, maybe they work in a corporate intranet. Doesn’t matter, the need exists.

          – Other people have a small enough % of legacy users that they feel justified in leaving those users behind. Maybe that’s ok, maybe it isn’t. Doesn’t matter, it’s their choice.

          Another note, <=IE9 is not the only browser that doesn't support Flexbox. Old versions of Opera and Opera Mini lack support as well. Many other older browsers from every vendor include only partial support. And yes, I can hear you all already: "Nobody uses those browsers". That's not true. Where I work we have high traffic numbers, and when you add up all non-supporting browsers including IE, it reaches a number that is low in % (less than 2%) but high in the raw number of visitors (~20,000/mo), and therefore disqualifies the use of Flexbox.

          • m

            I wonder if Opera Mini understands CSS. That browser seems to be incapable of anything.

        • ergreger is still right in what they’re saying though. You’re over-engineering something that is way simpler.

        • Alan Colyer

          just weighing in on the supporting old browsers debate… as others have said, go with your own analytics. Everyone uses IE8? better support it. They don’t? Use the shiny.

          To add to it, it’s worth nothing that IE8,9 and 10 have officially reached end of life and microsoft no longer support them, XP, vista, or Windows 8 (8.1 still supported). We just ditched support for those browsers based on both this and reviewing our own analytics, and discovering that IE has a vanishingly small market share these days (our users atleast) and of those using it, less than half a percent used anything other than IE11. That’s almost err…. one person per two hundred… and if the worst that happens is their fig caption text doesn’t center, I’d call that a win.

          https://www.microsoft.com/en-gb/WindowsForBusiness/End-of-IE-support

        • wonkeythemonkey

          Browser support is not all-or-nothing. The percentage of your users still stuck on an old version of IE is only part of the question you should be asking. The other part is whether this feature, if it fails in someone’s browser, will impact their experience in a meaningful way.

          What will happen in this flexbox solution if a user visits the site in IE 8 or 9? The caption text will fail to center when the line is short. That’s all! For my money, that’s a worthy tradeoff. In exchange for a small formatting difference for a small minority of users, I get a more maintainable and future-proof codebase.

      • Brendan Patterson

        So incorrect.

      • People can get way to hung up on the notion of browser support. @MoOx:disqus’s suggestion here is a perfect example of progressive enhancement, in my opinion it’s totally OK in this use case to use flexbox because the browsers that don’t support it will simply align all caption text to the left. Not the end of the world! It’s also worth remembering that browser vendors directly react to the usage of new css properties (sure flexbox isn’t exactly new anymore but you get my point), the more us developers use emerging properties the more pressure we can put on browser vendors to increase support and ultimately make CSS even better.

    • ergreger

      Please don’t overuse flexbox for elementay css stuff.

  • Pingback: Aligning Text Smartly in CSS | Tech +()

  • evild70

    If the client will buy off on some captions being centered and others left-aligned this works perfectly.

    • Tony Scialdone

      Thanks for pointing this out. I was entranced by new knowledge, but hadn’t yet considered that I’ve never worked with a designer that would align text in different ways like this. It’s interesting, and may have other, more usable, implications, but I can’t see this happening in real life. =)

    • I think the scenario is not so unreal. 🙂 The “default” solution of having a single line aligned left looks quite weird. This one looks much better and usually clients like stuff that looks good.

  • Pingback: Aligning Text Smartly in CSS | SeoRocketBar Network()

  • Pingback: Aligning Text Smartly in CSS - ADD_DanieleMilana()

  • Pingback: Aligning Text Smartly in CSS - Browser Zone()

  • Very good =)

  • Pingback: Aligning Text Smartly in CSS – Design Library()

  • Pingback: [DigitalScholarship] [webdev] Web Design Update: April 14 | tourismhospitalityrecreationandsportsmanagement()

  • Pingback: [DigitalScholarship] [webdev] Web Design Update: April 14 | sportmedblog()

  • Pingback: [DigitalScholarship] [webdev] Web Design Update: April 14 | statisticssources()

  • Pingback: [DigitalScholarship] [webdev] Web Design Update: April 14 – educatorgold()

  • Pingback: [DigitalScholarship] [webdev] Web Design Update: April 14 | digitalscholarshipandscholarlypublication()

  • Pingback: Aligning Text Smartly in CSS - Astound.Media()

  • Patrik Jarl

    Kinda smart. I like it.

  • thanks! very cool tip, as i was thinking about this very issue just recently.

  • Pingback: Bildunterschriften mit CSS immer perfekt ausrichten | kulturbanause® blog()

  • Pingback: [CSS] 译文:CSS 让对齐文本更智能 | 技术学习小组()

  • Pingback: Responsive CSS Patterns without Media Queries()