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

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.

(47)(1)



Source link

We're happy to share this resource that we found. The content displayed on this page is property of it's original author and/or their organization.

Leave a Reply