In order for a web application to render on a variety of devices (mobile, tablet, laptop, desktop), it needs to be “responsive”. Meaning the same website can have specific rules written into JavaScript, HTML, and CSS to make it adapt to the size of the screen the browser is running on.
In this post I’ll cover how to make something align on the screen according to what device the user is on. For example, on a desktop view, you may have some header text that you want to align right horizontally. But for the same page and header text rendered on a mobile phone, you may decide it looks better center aligned horizontally.
Let’s use the above example, and see how we can accomplish this. First let’s define the following CSS:
@media (max-width: 768px) { .responsive-text-align { text-align: center; } } @media (min-width: 768px) { .responsive-text-align { text-align: right; } }
We’ve created a CSS class called responsive-text-align. You’ll notice that it has two settings: max-width: 768px and min-width: 768px. This tells your browser which setting to use when the screen size is either lass than 768px, or greater than 768px. If we assume that a standard mobile screen is 768px across, the max-width: 768px setting will get applied to the webpage when it is rendered on a mobile screen.
You’ll also notice that for the two different screen sizes, we specify different text-align properties. This allows the text alignment to be determined dynamically, or rather, “responsively”.
To use this CSS class, here’s what your HTML would look like (using bootstrap):
<div class="row"> <div class="col-sm-12 responsive-text-align">Align this text responsively</div> </div>
And voila! The text will start aligning according to the rules for the responsive-text-align CSS class, based on what screen size the webpage is rendered in.