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


Codever Logo

(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:

  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

Featured image courtesy of 2nix / FreeDigitalPhotos.net

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading