Translator: Front-end wisdom

Original text: medium.com/@bretcamero…

CSS is a unique language. This may seem simple at first glance, but some effects that seem simple in theory are often not so obvious in practice.

In this article, I’m going to share some useful tips and tricks that represent my key progress in learning CSS. This article is not intended to demonstrate how complex CSS can become. Instead, it shares some useful tips that are unlikely to be found in most CSS tutorials.

To read more quality articles pleaseJabber at the GitHub blog, a hundred quality articles a year waiting for you!

1. Sticky Footer

This is a very common requirement, but it can be a challenge for beginners.

For most projects, regardless of the size of the content, you want the footer to be at the bottom of the screen — if the content of the page passes through the view port, the footer should be adjusted.

Prior to CSS3, it was difficult to achieve this effect without knowing the exact height of the foot. Although we call it sticky footer, you can’t solve this problem simply with Position: sticky because it blocks content.

Today, the most compatible solution is to use Flexbox. The main approach is to use the lesser-known flex-grow attribute on the div that contains the main content of the page. In the example below, I use the main tag.

Flex-grow controls how many Flex items populate their containers relative to other Flex elements. When the value is 0, it doesn’t grow, so we need to set it to 1 or more. In the example below, I use the shorthand property Flex: Auto, which sets flex-grow to 1 by default.

To prevent any unnecessary behavior, we can also add flex-shrink: 0 to the footer TAB. Flex-shrink is actually the opposite of flex-growth, which controls the flex element to shrink to the size appropriate for its container. Setting it to 0 just prevents the footer tag from shrinking and ensures that it retains its size.

    // html
    <div id="document"> <main> <h1>Everything apart from the footer goes here</h1> <p>Add more text here, to see how the footer responds! </p> </main> <footer> <h1>The footer goes here</h1> </footer> </div>Copy the code


    // css
    #document { 
        height: 100vh;
        display: flex;
        flex-direction: column;
    }
    
    main {
      flex: auto;
    }
    
    footer {
        flex-shrink: 0;
    }
    
    /* Other styling elements, that are not necessary forthe example */ * { margin: 0; font-family: Candara; } h1, p { padding: 20px; } footer { color: white; background: The url (https://images.unsplash.com/photo-1550795598-717619d32900?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=c rop&w=676&q=80); background-position: center; background-repeat: no-repeat; background-size: cover; } footer > h1 { text-shadow: 1px 1px 4px# 00000080;
    }
Copy the code

View the demo

2. Zoom-on-Hover

Zoom-on-hover effects are a great way to draw attention to a clickable image. When the user hovers over it, the image enlarges slightly, but its size remains the same.

To achieve this effect, you need to wrap the IMG tag around a div tag.

To make this effect work, set the parent element’s width and height, and make sure overflow is set to hidden. Then, you can apply any kind of transform animation effect to the inner image.

// html <div class="img-wrapper"> <img class="inner-img" src="https://source.unsplash.com/random/400x400" /> </div> <! -- Additional examples --> <div class="img-wrapper"> <img class="inner-img" src="https://source.unsplash.com/random/401x401" width="400px" height="400px" /> </div> <div class="img-wrapper"> <img class="inner-img" src="https://source.unsplash.com/random/402x402" width="400px" height="400px" /> </div>Copy the code


// css
.img-wrapper {  
  width: 400px;
  height: 400px;
  overflow: hidden; 
}

.inner-img {
  transition: 0.3s;
}

.inner-img:hover {
  transform: scale(1.1);
}
Copy the code

View the demo

3. Real-time night mode

If you’re looking for a quick way to apply a “night mode” skin to your site, use the Invert and Hue-rotate filters.

Filter: invert() ranges from 0 to 1, where 1 changes from white to black.

Filter: hue-rotate() Changes the color content of elements so that they have more or less the same separation level. The value ranges from 0deg to 360deg.

By combining these effects on the body tag, you can quickly try out the site’s night mode (note that in order to affect the background, you must give it a color).

Using these Settings, we can give Google’s home page an instant makeover:

4. Key points of customization

To create custom bullet points for unordered lists, use the Content attribute and ::before pseudo-elements.

In the CSS below, I use.complete and.incomplete classes to distinguish between two different types of bullet points.

ul { list-style: none; } ul.complete li::before {content: '🗹 '; } ul.incomplete li::before {content: '☐ '; }Copy the code

View the demo

Extra use: Breadcrumb navigation

There are many more useful ways to use the Content attribute, and I can’t resist introducing one more here.

Because the slashes and other symbols used to separate bread crumbs are stylized, it makes sense to define them in CSS. As with many examples in this article, this effect relies on the pseudo-class — Last-Child — provided in CSS3:

. Breadcrumb a:first-child::before {content: "» "; } .breadcrumb a::after { content: " /"; } .breadcrumb a:last-child::after { content: ""; }Copy the code

View the demo

5. Parallax Images

This eye-catching effect is becoming increasingly popular as it can bring life to a page as the user scrolls it.

When the normal image of a page moves as the user scrolls, the parallax image looks fixed — only the window visible through it moves.

Only CSS example

// html <div class="wrapper"> <h1>Scroll Down</h1> <div class="parallax-img"></div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima  veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et  voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p> </div> <div class="wrapper"> </div>Copy the code


// css .wrapper { height: 100vh; } .parallax-img { height: 100%; background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; } /* Other styling elements, that are not necessary for the example */ body { margin: 0; background: #000; } * { font-family: Candara; color: white; } h1 { margin: 15px; text-align: center; } p { margin: 15px; The font - size: 1.1 rem; } .parallax-img { background-image: url('https://source.unsplash.com/random/1920x1080'); }Copy the code

View the demo

CSS + JavaScript examples

For more advanced effects, you can use JavaScript to add movement to the image as the user scrolls.

// html <div class="block"> <img src="https://unsplash.it/1920/1920/? image=1005" data-speed="-1" class="img-parallax"> <h2>Parallax Speed -1</h2> </div> <div class="block"> <img src="https://unsplash.it/1920/1920/? image=1067" data-speed="1" class="img-parallax"> <h2>Parallax Speed 1</h2> </div> <div class="block"> <img src="https://unsplash.it/1920/1920/? Gravity =center" data-speed="-0.25" class="img-parallax"> < H2 > parallax speed-0.25 </h2> <div > <div class="block"> <img src="https://unsplash.it/1920/1920/? Class ="img-parallax"> <h2>Parallax speed 0.25</h2> <div > <div class="block"> <img src="https://unsplash.it/1920/1920/? Random "data-speed="-0.75" class="img-parallax"> < H2 >Parallax speed-0.75 </ H2 > </div> <div class="block"> <img src="https://unsplash.it/1920/1920/? Blur "data-speed="0" class="img-parallax"> < H2 >Parallax speed 0 </h2> </div>Copy the code


/ / CSS @ import url (https://fonts.googleapis.com/css?family=Amatic+SC:400, 700); html, body{ margin: 0; padding: 0; height: 100%; width: 100%; font-family: 'Amatic SC', cursive; } .block{ width: 100%; height: 100%; position: relative; overflow: hidden; font-size: 16px; } .block h2{ position: relative; display: block; text-align: center; margin: 0; top: 50%; transform: translateY(-50%); font-size: 10vw; color: white; font-weight: 400; } .img-parallax { width: 100vmax; z-index: -1; position: absolute; top: 0; left: 50%; transform: translate(-50%,0); pointer-events: none }Copy the code


// js // I know that the code could be better. // If you have some tips or improvement, please let me know. $('.img-parallax').each(function(){ var img = $(this); var imgParent = $(this).parent(); function parallaxImg () { var speed = img.data('speed'); var imgY = imgParent.offset().top; var winY = $(this).scrollTop(); var winH = $(this).height(); var parentH = imgParent.innerHeight(); // The next pixel to show on screen var winBottom = winY + winH; // If block is shown on screen if (winBottom > imgY && winY < imgY + parentH) { // Number of pixels shown after block appear var imgBottom = ((winBottom - imgY) * speed); // Max number of pixels until block disappear var imgTop = winH + parentH; // Porcentage between start showing until disappearing var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50)); } img.css({ top: imgPercent + '%', transform: 'translate(-50%, -' + imgPercent + '%)' }); } $(document).on({ scroll: function () { parallaxImg(); }, ready: function () { parallaxImg(); }}); });Copy the code

View the demo

6. Crop the image to animate

As with sticky footers, cropping images before CSS3 can be tricky. Now, we have two properties that make cropping easy, Object-Fit and Object-Position, which together allow you to change the size of the image without affecting its aspect ratio.

Previously, it was always possible to crop an image in a photo editor, but a big advantage of cropping an image in a browser is the ability to resize an image as part of an animation.

To demonstrate this effect as simply as possible, the following example triggers it using the tag. This way, we can take advantage of CSS’s: Checked pseudo-class, and we don’t need to use any JavaScript:

// html <input type="checkbox" /> <br /> <img src="https://source.unsplash.com/random/1920x1080" alt="Random" /> input { The transform: scale (1.5) margin: 10 px 5 px; } img { width: 1920px; height: 1080px; transition: 0s; } input:checked +br + img{ width: 500px; height: 500px; object-fit: cover; object-position: left-top; transition: width 2s, height 4s; }Copy the code

View the demo

7. Blend Modes

If you have experience with Photoshop, you probably know how powerful its different blending modes can be to create interesting effects. But did you know that most of Photoshop’s blend modes can also be used in CSS?

When the image is set to background-color:lightblue; blend-mode:difference ; And this is what Medium’s home page looks like:

Also, background isn’t the only way to take advantage of mixed patterns. The mix-blending-mode attribute allows you to blend elements with their existing background. For example, create this effect with the following style:

    // html
    <h1>This is an example title</h1>
Copy the code


// css h1 { mix-blend-mode: color-dodge; font-family: Candara; font-size: 5rem; text-align: center; margin: 0; padding: 20vh 200px; color: lightsalmon; } html, body { margin: 0; background-color: white; } body { background-image: The url (https://images.unsplash.com/photo-1550589348-67046352c5f3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=c rop&w=1353&q=80); background-repeat: no-repeat; background-size: cover; min-height: 100vh; overflow: hidden; }Copy the code

View the demo

8. Pinterest – style image

CSS Grid and Flexbox make it easier to implement many different types of responsive layouts and allow us to easily center elements vertically on a page — something that was previously very difficult.

One layout style they don’t fit well, however, is the one Pinterest uses, where the vertical position of each element changes according to the height of the element above it.

The best way to do this is to use CSS’s suite of column properties. These are most often used to create multiple newspaper-style text columns, but this is another good use case.

To do this, wrap the element in a div and provide the wrapper with column-width and column-gap attributes.

Then, to prevent any element from being split into two columns, use column-break-inside:avoid to add it to a single element.

// html <div id="columns"> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/cinderella.jpg"> <figcaption>Cinderella wearing European fashion of the mid-1860's </ figfigure > </figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/rapunzel.jpg"> <figcaption>Rapunzel, Clothed in 1820's period fashion</ figfigure > <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/belle.jpg"> <figcaption>Belle, Based on 1770's French Court Fashion </figure> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/mulan_2.jpg"> <figcaption>Mulan, based on the Ming Dynasty period</figcaption> </figure> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/sleeping-beauty.jpg"> <figcaption>Sleeping Beauty, based on European fashions in 1485</figcaption> </figure> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/pocahontas_2.jpg"> <figcaption>Pocahontas based on 17th century Powhatan costume</figcaption> </figure> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/snow-white.jpg"> <figcaption>Snow White, based on 16th century German fashion</figcaption> </figure> <figure> <img src="//s3-us-west-2.amazonaws.com/s.cdpn.io/4273/ariel.jpg"> <figcaption>Ariel wearing an evening gown of the 1890 's < / figcaption > < figure > < figure > < img SRC = "/ / s3-us-west-2.amazonaws.com/s.cdpn.io/4273/tiana.jpg" > < figure> Tiana wearing the < I >robe de style</ I > of the 1920's </figure> <small>Art &copy; <a href="//clairehummel.com">Claire Hummel</a></small> </div>Copy the code


// css
@font-face{font-family:'Calluna';
 src:url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/callunasansregular-webfont.woff') format('woff');
}
body {
    background: url(//subtlepatterns.com/patterns/scribble_light.png);
  font-family: Calluna, Arial, sans-serif;
  min-height: 1000px;
}
#columns {
    column-width: 320px;
    column-gap: 15px;
  width: 90%;
    max-width: 1100px;
    margin: 50px auto;
}

div#columns figure {
    background: #fefefe;
    border: 2px solid #fcfcfc;
    box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4);
    margin: 0 2px 15px;
    padding: 15px;
    padding-bottom: 10px;
    transition: opacity .4s ease-in-out;
  display: inline-block;
  column-break-inside: avoid;
}

div#columns figure img {
    width: 100%; height: auto;
    border-bottom: 1px solid #ccc;
    padding-bottom: 15px;
    margin-bottom: 5px;
}

div#columns figure figcaption {
  font-size: .9rem;
    color: #444;
  line-height: 1.5;
}

div#columns small { 
  font-size: 1rem;
  float: right; 
  text-transform: uppercase;
  color: #aaa;
} 

div#columns small a { 
  color: #666; 
  text-decoration: none; 
  transition: .4s color;
}

div#columns:hover figure:not(:hover) {
    opacity: 0.4;
}

@media screen and (max-width: 750px) { 
  #columns { column-gap: 0px; }
  #columns figure { width: 100%; }
}
Copy the code

View the demo

The above example is also a good example of CSS: Not () pseudo-classes. He uses it with :hover, so that all but hovering elements fade out.

Other resources

Overall, I hope that the examples below have illustrated some useful CSS effects, and may even draw your attention to some features you haven’t seen before.

Features like this don’t fall into the category of “simple tricks” and can be explored quite deeply on their own. So I’m not going to describe them here, but here are some great resources to learn about them:

Keyframe animation

  • Css-tricks.com/snippets/cs…

Scroll-snapping

  • Css-tricks.com/practical-c…

Multi-level navigation

  • Bradfrost.com/blog/post/c…

The 3 d effect

  • www.the-art-of-web.com/css/3d-tran…

CSS print

  • www.the-art-of-web.com/css/3d-tran…

  • Edutechwiki. Unige. Ch/en/CSS_for_…

Design principles

  • material.io/

Your likes are my motivation to keep sharing good things.

communication

Dry goods series of articles summarized as follows, feel good point Star, welcome to add groups to learn from each other.

Github.com/qq449245884…

I am Xiaozhi, the author of the public account “Big Move the world”, and a lover of front-end technology. I will often share what I have learned to see, in the way of progress, mutual encouragement!

Pay attention to the public number, background welfare, you can see the welfare, you know.