DEV Community

Cover image for CSS One-Liners to Improve (Almost) Every Project
Alvaro Montoro
Alvaro Montoro

Posted on • Originally published at alvaromontoro.com

CSS One-Liners to Improve (Almost) Every Project

Most of these one-liners will be one declaration inside the CSS rule. In some cases, the selector will be more than just a simple element; in others, I will add extra declarations as recommendations for a better experience, thus making them more than a one-liner —my apologies in advance for those cases.

Some of these one-liners are more of a personal choice and won't apply to all websites (not everyone uses tables or forms). I will briefly describe each of them, what they do (with sample images), and why I like using them. Notice that the sample images may build on top of previous examples.

Here's a summary of what the one-liners do:

  • Limit the content width within the viewport
  • Increase the body text size
  • Increase the line between rows of text
  • Limit the width of images
  • Limit the width of text within the content
  • Wrap headings in a more balanced way
  • Form control colors to match page styles
  • Easy-to-follow table rows
  • Spacing in table cells and headings
  • Reduce animations and movement

Limit the content width in the viewport



body {
  max-width: clamp(320px, 90%, 1000px);
  /* additional recommendation */
  margin: auto;
}


Enter fullscreen mode Exit fullscreen mode

Adding this one-liner will reduce the content size to occupy 90% of the viewport, limiting its width between 320 and 1000 pixels (feel free to update the minimum and maximum values).

This change will automatically make your content look much nicer. It will no longer be a vast text block but something that looks more structured and organized. And if you also add margin: auto; to the body, the content will be centered on the page. Two lines of code make the content look so much better.

Side-by-side comparison of change. Left side (before): a big block of text. Right side (after): text with padding on the sides. Still big but with more spaces.

Aligned and contained text looks better than a giant wall of text


Increase the text size



body {
  font-size: 1.25rem;
}


Enter fullscreen mode Exit fullscreen mode

Let's face reality: browsers' default 16px font size is small. Although that may be a personal opinion based on me getting old 😅

One quick solution is to increase the font size in the body. Thanks to the cascade and em units browsers use, all the text on a web page will automatically increase.

side by side comparison. Left (before): column with text. Right (after): column with text at a larger size.

Larger text size makes things easier to read.


Increase the space among lines



body {
  line-height: 1.5;
}


Enter fullscreen mode Exit fullscreen mode

Another preference for improving readability and breaking the dreaded wall of text is increasing the space between lines in paragraphs and content. We can easily do it with the line-height property.

side by side comparison. Left (before): column with text. Right (after): column with text (more spaced).

Spaces between lines break the wall of text and the rivers of white.

This choice (with the previous two) will considerably increase our page's vertical size, but I assure you the text will be more readable and friendlier for all users.


Limit the size of images



img {
  max-width: 100%;
}


Enter fullscreen mode Exit fullscreen mode

Images should be approximately the size of the space they will occupy, but sometimes, we end up with really long pictures that cause the content to shift and create horizontal scrolling.

One way to avoid this is by setting a maximum width of 100%. While this is not a fool-proof solution (margins and paddings may impact the width), it will work in most cases. 

side by side comparison. Left (before): an image overflows the content size causing scrollbars to appear. Right (after): the image adjust to the content size.

Prevent horizontal scrolling and make images flow better with the text


Limit the width of text within the content



p {
  max-width: 65ch;
}


Enter fullscreen mode Exit fullscreen mode

Another tactic to avoid the dreaded wall of text and rivers of space is to apply this style even in conjunction with the max width in the body. It may look unnecessary and sometimes weird, as paragraphs will be narrower than other elements. But I like the contrast and the shorter lines.

A value of 60ch or 65ch has worked for me in the past, but you can use a different value and adjust the max width to match your needs. Play and explore how it looks on your web page.

side by side comparison. Left (before): the text occupies the whole width. Right (after): the text occupies most of the width.

Break the bigger chunks of text into smaller blocks for readability


Wrap headings in a more balanced way



h1, h2, h3, h4, h5, h6 {
  text-wrap: balance;
}


Enter fullscreen mode Exit fullscreen mode

Headings are an essential part of the web structure, but due to their larger size and short(-er) content, they may look weird. Especially when they occupy more than one line. A solution that will help is balancing the headings with text-wrap.

Although balance seems to be the most popular value for text-wrap, it is not the only one. We could also use pretty, which moves an extra word to the last row if needed instead of balancing all the content. Unfortunately, pretty has yet to count on broad support.

side by side comparison. Left (before): a heading occupies two rows, the second one has only 1 word. Right (after): the heading occupies two rows of similar width.

Balanced wrapping can improve visibility and readability


Form control colors to match page styles



body {
  accent-color: #080; /* use your favorite color */
}


Enter fullscreen mode Exit fullscreen mode

Another small change that does not have a significant impact but that makes things look better. Until recently, we could not style native form controls with CSS and were stuck with the browser display. But things have changed.

Developing a whole component can be a pain, but setting a color that is more similar to the rest of the site and the design system is possible and straightforward with this one-liner.

side by side comparison. Left (before): form controls are the default blue . Right (after): form controls color match the heading and link colors (green).

It's the small details (and colors) that bring the page together


Easy-to-follow table rows



:is(tbody, table) > tr:nth-child(odd) {
  background: #0001; /* or #fff1 for dark themes */
}


Enter fullscreen mode Exit fullscreen mode

We must use tables to display data, not for layout. But tables are ugly by default, and we don't want data to look ugly. In particular, one thing that helps organize the data and make it more readable is having a zebra table with alternating dark/light rows.

The one-liner displayed above makes achieving that style easy. It can be simplified to be only tr without considering the tbody or table parent, but it would also apply to the table header, which we may not want. It's a matter of taste.

side by side comparison. Left (before): all table rows are white. Right (after): even table rows are slightly darker.

Easier to follow the data horizontally (by row)


Spacing in table cells and headings



td, th {
  padding: 0.5em; /* or 0.5em 1em... or any value different from 0 */
}


Enter fullscreen mode Exit fullscreen mode

One last change to make tables more accessible and easier to read is to space the content slightly by adding padding to the table cells and headers. By default, most browsers don't have any padding, and the text of different cells touches, making it confusing to differentiate where one begins and the other ends.

We can change the padding value to adjust it to our favorite size. However, avoid overdoing it to avoid unnecessary scrolling or too much blank space.

side by side comparison. Left (before): table cells text content is altogether. Right (after): table cells content is clearly separated from other table cells.

Easier to follow data horizontally and vertically


Reduce animations and movement



@media (prefers-reduced-motion) {
  *, *::before, *::after {
    animation-duration: 0s !important;
    /* additional recommendation */
    transition: none !important;
    scroll-behavior: auto !important;
  }
}


Enter fullscreen mode Exit fullscreen mode

Okay, okay. This code is way more than a one-liner. It has a one-liner version (removing animations by setting their duration to zero seconds), but other things on a web page make elements move.

By setting these declarations inside the prefers-reduced-motion media query, we will respect the person's choice to have less movement. This approach is somewhat radical because it removes all movement, which may not necessarily be the user's intent -it is "reduced motion" and not "no motion." We can still preserve movement on a case-by-case basis if appropriate.

side by side comparison. Left (before): an image moves over a web page. Right (after): the image is static.

No animations? No problem!

Top comments (47)

Collapse
 
cavo789 profile image
Christophe Avonture

Nice. Images before and after are really meaningful.

Collapse
 
ziizium profile image
Habdul Hazeez

I was about to say the same.

Collapse
 
zmyaro profile image
Zachary Yaro

Most of these are great, but please please please don't override the user's preferred body text size unless you are using a typeface that needs it! A low vision person likely already increased xer preferred text size across xer whole system; don't assume you know better than xem!

Collapse
 
terabytetiger profile image
Tyler V. (he/him) • Edited

I think it's worth clarifying that the code in the article does account for the user's browser font size preferences.

Setting something like px specifically would override it but using rem or em adjusts based on the base text size the user has set in the browser. 😊

Collapse
 
zmyaro profile image
Zachary Yaro

Yes, I know how rems work, but a person who has already increased the base font size to xer comfort doesn't need you increasing it further, and a person who doesn't want the base font size enlarged doesn't need you overriding xer preference either.

Collapse
 
e1uone profile image
Dmitry

So is there any way to know if the user has changed a default browser font-size or not?

Collapse
 
neilsentence profile image
Nils Sens • Edited

Good comment. But if you specifically accommodate people with low vision, please also accommodate people who need standard English (myself, I have a complex migraine issue that started in the Philippines; lots of non-standard English there...). My brain tries to decypher for a second "xer" etc... gets stuck, and as some kind of "protective measure" this migraine kicks in, completely deactivating my brain's language center for a good 15 minutes. It was diagnosed as mild stroke (transitory ischaemic attack), until a really good neurologist correctly diagnosed it as complex migraine, luckily taking me off blood thinners again. A bit of introspection lead me to the realization that it's a "shutdown response", and I can - somehow - manage. Coming full circle, low vision and my condition have something in common: I get this kind of tunnel vision, and visual artifacts during an attack. I'm not sure if you should put your own ... freedom of expression ... over my mental wellbeing. Which I would understand, if you didn't... maybe the designer's choice not to accommodate people with bad eyesight, and your choice not to change your way of writing to respect people like me, are related, and both (I guess) to be respected. However, if it doesn't cost an arm and a leg, both you and the designer could try to adhere to some kind of beneficial standards.

Collapse
 
zmyaro profile image
Zachary Yaro • Edited

I agree accessibility is extremely important. I haven't heard of that condition before, and I am curious to learn more! What forms of “non-standard English” trigger that response, which standard of English does your condition tend to adhere to, and does it tend to center around spelling, grammar, sentence structure, or multiple of those?

You seem to be using U.S. spellings, so do you struggle with British spellings? Do you also struggle with regional dialects (I myself have lived in Virginia and the Boston area, and have noticed each's distinct local colloquialisms), different fields' professional jargon, made-up terms in works of fiction (as Shakespeare was notorious for), or slang from various decades? I noticed you also included liberal use of ellipses, and used hyphens where dashes would have technically been more correct, so is non-standard punctuation less triggering than non-standard terminology? Are there particular practices you find writers and developers can take to help mitigate your symptoms besides avoiding the use of one particular 51-year-old neopronoun? Thank you in advance for any insights you are willing to share or any links you have where I can learn more about this condition for my accessibility work!

Thread Thread
 
neilsentence profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Nils Sens

You "counter" my above comment by splitting hairs about hyphens or dashes? What I was referring to is not if a line is a millimeter longer, or if something is spelled - or spelt - the British or American way, but when a normal sentence suddenly gets interrupted by words like xer xur xor xou or other stuff that doesn't seem to be a word and not in the context of fantasy stories (name of a wizard or monster or whatnot, you get the point).

I get slightly dizzy just looking back at the previous sentence. My condition is also triggered by wrong syntax, and honestly also by the wrong use of "their" / "there" / "they're", but there, it only causes a slight nausea, not a complete breakdown. I'll try to dig up some profiles on a dating site I've used before (not kidding), where it got really bad (I'm guessing here) - causing the condition to develop in the first place. I hope that by adding, that these words ("neopronouns") are 51 years old ('neo'?), you're not trying to make it somehow appear as if I'm protesting something long-standing or long established. Because: no, they're not established. For two reasons:

  1. it goes back to way before the 1970s. Wikipedia mentions the 18th century!

  2. weird pronouns will never really be established, because there's simply no consensus even among users: as soon as you think "singular they" has become a thing, "ze" gets introduced by someone else, then you say "OK, let's settle on 'ze'!" and xou, xee, xnghu get invented by someone else who finds... I guess by that time ... "they" boring(?). Meaning that very subgroup that is so fond of an alternative lexicon keeps stirring it up so it doesn't actually settle.

According to the article, there's only little actual support by the actual LGBTQ+ community, and also "opposition to the idea in both the cisgender and transgender communities. Many people find them unfamiliar and confusing to use. Some have said that use of neopronouns, especially noun-self pronouns, comes from a position of privilege, makes the LGBT+ community look like a joke, or that the attention placed on neopronouns pulls focus away from larger, more important issues, such as transphobic bullying, the murder of trans people, and suicide. Noun-self pronouns have been viewed by some as unhelpful and unnecessary."

I really wish it's my transphobia or conservativism or whatever neuroticism I might have developed from meeting too many crazy folks, but it's not limited to funky pronouns. I'm wondering whether there are others who suffer from the same or a similar condition (couldn't tell)... Imagine I'd rewrite this whole message, replacing "by" by "vey" and "it" by "og". You'd be uncomfortable reading it, even without my condition.

You'd struggle, and feel a little stupid for a second, until you realize my language is off. Then you'd start judging me, probably for making you question your own IQ. Those are "functional words" you say - so are pronouns.

My plea is simple: avoid neopronouns. Not even the LGBTQ-community adopts them (4%!). Just people who try to express how tolerant or nice they are. I could do the same with other words, but I put the reader's comfort above my own creativeness. I really don't give a damn about LGBTQ, swapping out vowels in other words would also give me a hard time.

Thread Thread
 
neilsentence profile image
Nils Sens

I'm not sure if I'm alone with this, or if there are others who feel the same or similar.

Collapse
 
papylataupe profile image
Papy-La-Taupe

wich unit mesurement is xem ? i know about rem, and em but... is it like a new type for phone like svh/dvh ?

Collapse
 
zmyaro profile image
Zachary Yaro

“Xe”/“xem”/“xer”/“xers”/“xerself” are unofficial explicitly singular gender-neutral alternatives to “he”/“him”/“his”/“his”/“himself” or “she”/“her”/“her”/“hers”/“herself”. More recently, so-called “neopronouns” have gotten more mainstream attention in association with the LGBTQIA+ community, but I first became aware of them as a writer looking for an explicitly singular alternative to the ambiguous “they”, and they have long since become a regular part of my vocabulary. I hope that helps; I didn't intend confusion and generally try to use code styling when writing CSS units like rem, em, vh, svh, lvh, dvh, etc.!

Collapse
 
tkarika profile image
tkarika

Absolutely agree.

Collapse
 
obedsmart profile image
Obed✨✨

It’s better to use percentages instead of making hard rule

Collapse
 
zmyaro profile image
Zachary Yaro

It is good to use relative units (such as % or em) for font sizes in general, yes, but the base font size should also be left at 1rem in most cases rather than assuming the user set it to an undesired size and you know better!

Collapse
 
best_codes profile image
Best Codes • Edited

Nice post! I especially appreciate two things:

  • The images (before / after)
  • The #listicle tag (even though this is a good listicle)

Keep writing!

Collapse
 
alvaromontoro profile image
Alvaro Montoro

I dislike listicles. I really do. I find that, in general, they are lazy ways to present content, often mediocre, and more often than not they make statements that should have a ton of "ifs" attached to them (but don't). I tend to write them as "subtweets"/responses to other listicles I find online... Unfortunately, they have more impact than any other type of article I write.

Collapse
 
best_codes profile image
Best Codes

Unfortunately, they have more impact than any other type of article I write.

Yup, I've experienced that myself. I wish actual good content was more popular.

Collapse
 
miialainen profile image
Miia

Nice, did not know of accent-color, that is really useful!

Collapse
 
mishmanners profile image
Michelle Duke

Loving the code snippets, and the images help illustrate your points 😄

Collapse
 
mishmanners profile image
Michelle Duke

This really took me back to typography days.

Collapse
 
moataz_osama_eb1c1ea9f41a profile image
Moataz Osama

Nice. checkbox color change

Collapse
 
chandra_pantachhetri profile image
Chandra Panta Chhetri

As others have mentioned, I also appreciate the before and after pictures. The clamp & text-wrap balance looks useful

Collapse
 
shricodev profile image
Shrijal Acharya

These are really neat tricks. Now I need to find the Tailwind equivalent classes for some of these.

text-wrap: balance;
Enter fullscreen mode Exit fullscreen mode

This was my discovery of the day.

Collapse
 
terabytetiger profile image
Tyler V. (he/him)

It looks like they all exist - the one that's the least obvious to find is the max width 65ch, which is max-w-prose

Collapse
 
19lilly profile image
Rozvita Lilly Štiglinc

tailwindcss.com/docs/text-wrap tailwind equivalent is


text-balance
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nnisarggada profile image
Nnisarg Gada

Do note that this does take up significant resources for the calculations and is therefore only recommended to be used for headings (as shown in the blog post)

Collapse
 
aqib_shoaib_460d14658d79a profile image
Aqib Shoaib

h1, h2, h3, h4, h5, h6 {
text-wrap: balance;
}
this property is not working with styled components, The IDE is giving me the warning of unknown property...i will provide the screenshort as well

Image description

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Maybe the plugin needs update? text-wrap: balance is widely supported now.

Collapse
 
aqib_shoaib_460d14658d79a profile image
Aqib Shoaib

I have the latest version installed. I even asked chatgpt about it. Chatgpt told me that this property is not standard property of CSS that is why it is being identified as Unknown.

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

text-wrap is definitely part of the CSS standard, and the balance value was added "recently" (years ago, although it was not implemented by browsers). You can check the W3C site with the information. In particular, the combination text-wrap: balance is already implemented and supported by all major browsers (as indicated in the MDN link from my previous comment).

Thread Thread
 
aqib_shoaib_460d14658d79a profile image
Aqib Shoaib

yes i too noticed that in the meanwhile, i will try using this property in normal way, instead of using styled component library,maybe that will work

Some comments may only be visible to logged-in visitors. Sign in to view all comments.