10 CSS Tricks You Need to Know About

Image for post
Image for post

1 — Truncate with Ellipsis (single line)

p {
/* use max-width so the ellipsis
only shows when reached that size */

max-width: 200px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: inline-block;

}

2 — Truncate with an ellipsis (multiple lines)

p {
/* old display option */
display: -webkit-box;
-webkit-box-orient: vertical;
/* max number of lines to show */
-webkit-line-clamp: 3;
/* needed for it to work */
overflow: hidden;
}

3 — Center vertically

.flex-vertically-center {
display: flex;
align-items: center;
}
img {
/* only for block tags */
display: inline-block;
vertical-align: middle;
}
.container {
position: relative;
}
.element {
/* change to fixed to center relative to the view */
position: absolute;
top: 50%;
transform: translateY(-50%);

}

4 — Center horizontally

.block-element {
margin: 0 auto;
/* use display only if
element is not block already */
display: block;
}
.container {
text-align: center;
}
.container {
position: relative;
}
.element {
/* change to fixed to center relative to the view */
position: absolute;
top: 50%;
transform: translateX(-50%);

}
.flex-vertically-center {
display: flex;
justify-content: center;
}

5 — Style next or previous siblings

.current ~ button {
/* the style you want */
}
.current + button {
/* the style you want */
}
button {
background: red;
}
.current,
.current ~ button {
background: initial;
}

6 — Style elements in a specific range

.box:nth-of-type(n+2):nth-of-type(-n+5) {
background: red;
}

7 — box-sizing

.box {
width: 200px;
height: 200px;
background: #eee;
padding: 20px;
}
.box {
width: 200px;
height: 200px;
background: #eee;
padding: 20px;
box-sizing: border-box;
}
Targets all elements and pseudo-elements*, *::after, *::before {
box-sizing: border-box;
}

8 — aspect ratio

.container {
width: 200px;
}
.box {
padding-top: calc((9/16) * 100%);
background: #eee;
}
.container {
width: 200px;
}
.box::after {
content: "";
display: block;

padding-top: calc((9/16) * 100%);
background: #eee;
}
.box {
aspect-ratio: 16 / 9;
}

9 — text around an image

Image for post
Image for post
.
img {
float: right;
shape-outside: url(some-url-to-your-image);
}

10 — is, matches, any and :where

section h1, 
article h1,
aside h1,
nav h1 {
font-size: 25px;
}
:is(section, article, aside, nav) h1 {
font-size: 25px;
}

Conclusion

Blog & YouTube Channel for Web, UI & Software Development - beforesemicolon.comyoutube.com/c/BeforeSemicolon

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store