Trick – how to make the length of a paragraph’s text responsive with media queries

In this post I will present you a simple trick about how to make the length of the text shown in a paragraph responsive. The example presented is written in Java Server Pages (JSP) and makes use of JavaServer Pages Standard Tag Library (JSTL), but you can use the same trick with other technologies and media queries as you will find out in the coming paragraphs.

The need

All of the podcasts and episodes present on Podcastpedia.org, have a description, whose length varies between 0 and 1000 characters (more than that is not stored in the database). To keep the length of that text shown to some extent responsive meaning not to get too long for small devices, I’ve decided that for screen with resolutions smaller than 720px, the length should not be more than 300 characters and for bigger resolutions should be limited to 600 characters (you know with podcasts you shouldn’t tell your story in text anyway…)

The trick

How did I achieve that?
Very simple:

  1. include in the html/JSP code the same information twice
  2. use the fn:substring() function to get different subsets of the string(one time 300, and the other time 600); I am sure there are similar functionalities offered by other languages/frameworks…
  3. use media queries to show and hide the paragraphs at the same time based on the screen’s width

HTML/JSP part

This is how it looks in JSP:

....................
<div class="ep_desc">
	${fn:substring(episode.description,0,300)}
</div>
<div class="ep_desc_bigger">
	${fn:substring(episode.description,0,600)}
</div>
....................

Code tip: You can find the source code for the JSP file on GitHub – episode_details_m.jsp

CSS part

The CSS code supporting this is the following:

@media screen and (min-width: 720px) {
    .ep_desc {
		display: none;
	 }
}

@media screen and (max-width: 719px) {
    .ep_desc_bigger {
		display: none;
	 }
}

Code tip: As you might recall from the post CSS Preprocessors – Introducing Sass to Podcastpedia.org, the CSS for Podcastpedia.org gets generated from SASS with Gulp.

Well, that’s it. If you have a better proposal to achieve this please leave a comment!!! 10x

Resources

Source code

Web

  1. Oracle – JavaServer Pages Standard Tag Library
Podcastpedia image

Adrian Matei

Creator of Podcastpedia.org and Codingpedia.org, computer science engineer, husband, father, curious and passionate about science, computers, software, education, economics, social equity, philosophy - but these are just outside labels and not that important, deep inside we are all just consciousness, right?

Featured image courtesy of 2nix / FreeDigitalPhotos.net

How to configure Nginx in production to serve an Angular app and reverse proxy NodeJS

Install Nginx on Ubuntu Server, understand configuration files, configure SSL, serve static files, reverse proxy Keycloak and NodeJS servers Continue reading