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

(P) Codever is an open source bookmarks and snippets manager for developers & co. See our How To guides to help you get started. Public bookmarks repos on Github âđ
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:
- include in the html/JSP code the same information twice
- 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âŚ
- 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
-
GitHub
- Repositories
- Relevant files
Web
Featured image courtesy of 2nix / FreeDigitalPhotos.net