Recently read the “CSS uncovered” this book, which introduces a lot of practical coding skills, often let a person have a sense of enlightenment, here will be some commonly used skills for summary and practice.

Vertical center

There are two common ways to center an element of unknown height vertically:

  • 1. Use absolute positioning and translate
//html
<div class="parent">
   <div class="child">center</div>
</div>

//css
.parent{
   height: 300px;
   width: 300px;
   position: relative;
   background-color: bisque;
}
.child{
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   padding: 30px;
   background-color: cornflowerblue;
}
Copy the code
  • 2. Flexbox-based solution

This is arguably the best solution, as Flexbox is designed specifically for these types of needs, although some older browser versions may not work well. Check out Caniuse, but modern browsers generally work fine.

.parent{
   height: 300px;
   width: 300px;
   background-color: bisque;
   display: flex;
   justify-content: center;
   align-items: center;
}
.child{
   padding: 30px;
   background-color: cornflowerblue;
}
Copy the code

The footer at the bottom

<body>
    <main>hello</main>
    <footer></footer>
</body>
Copy the code

On web sites, we expect footers to stick close to the bottom, regardless of page length. When the page is long enough, the display is fine. When the page is short, the footer will run up.An intuitive method is to use calc to calculate the minimum height of main:Min-height :calc(100vh-footer height);If the height of the footer is also determined by its contents, this would not work.

You can still solve this problem with Flexbox. First we need to set display: flex on the body element, because it is the parent of the two main blocks. When the parent element gets this property, it can trigger the “flex box layout model” on its children. We also need to set the flex-direction:column to make the flex direction vertical. Then, give main’s Flex property a value greater than 0 (such as 1).

body{
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
main{
  flex: 1;
  background-color: antiquewhite;
  padding:30px;
}
footer{
  padding:50px;
  background-color: rgb(48, 46, 46);
}
Copy the code

This way, no matter how many main and footer contents there are, the footer will stick close to the bottom of the page.Tip:

This Flex property is actually shorthand syntax for Flex-grow, Flex-shrink, and Flex-basis. Any element that sets a Flex value greater than 0 will be scalable; The flex value is responsible for controlling the size allocation ratio between multiple scalable elements. For example, in the example in front of us, if <main> is Flex: 2 and <footer> is Flex: 1, then the height of the content block will be twice the height of the footer. If you change their values from 2 and 1 to 4 and 2, the result is the same, because what really matters is their numerical proportions.Copy the code

Nine grid picture display

The photo display in Moments of Friends and Weibo will be different according to the number of different styles, this can also be achieved with pure CSS. The technique of setting styles according to the number of sibling elements in CSS Uncovered solves this problem.

We know that CSS has pseudo-class selectors related to sorting child elements, for example,

  • :nth-child(n) – matches the NTH child element that belongs to its parent
  • :nth-last-child(n) – matches the NTH penultimate child of its parent
  • :only-child – matches the only child element that belongs to its parent, equivalent to :nth-child(1):nth-last-child(1)

These selectors are easy to understand, but you can actually combine them to position elements more precisely.

In the following example, img:nth-child(2): nth-last-Child (3) positions the img elements that are second in the forward and third in the backward, that is, only the second in the forward with a total of 4 satisfies the condition. By increasing the margin-right of this element, you can “squeeze” the third image to the next row in the case of four images, achieving a four-square arrangement of four images. Img :only child: if there is only one image, the image must be displayed according to the scale of the image. Therefore, the image cannot be set to height and width. Instead, use max-height max-width to limit the maximum height/width of the image.

<p> What a lovely day! </p> <div class="album"> <img src="./images/bg.jpg" /> <img src="./images/cat2.jpg" /> <img src="./images/pic1.jpg" /> <img src="./images/pic2.jpg" /> <img src="./images/pic3.jpg" /> <img src="./images/pic4.jpg" /> <img src="./images/pic5.jpg" /> <img src="./images/pic6.jpg" /> <img src="./images/pic9.jpg" /> </div>Copy the code
.album{ margin-left: 50px; width: 342px; } img{ height: 110px; width: 110px; } img:only-child{ height: initial; Width: initial; max-width: 230px; max-height: 230px; } img:nth-child(2):nth-last-child(3){ margin-right: 110px; }Copy the code

Flexible background positioning

If you write a letter, put a mark at the end. We can position this as the background image in the lower right corner. The background-position attribute is used to set the position of the background image within the element. We setbackground-position: right bottom, the marker will be attached to the lower right corner.To keep the tag some distance from the border, you can setbackground-position: right 20px bottom 20px.If you want the background to be exactly the same distance from the border as the padding (even if you change the padding value), you can also change background-origin. Each element corresponds to three rectangles: the border box, the padding box, and the Content box. When we writebackground-position: right bottomThe default is the lower right corner of the padding box. If you want to align the bottom right corner of the Content box, you can change itBackground - origin: the content - box;

Another common use of background-position is a Sprite diagram. When there are many small ICONS used in a web page, we can combine them into a picture to reduce network requests. Use background-position to position different ICONS.For example, take a Sprite image where each icon is 200px in size and the spacing between the ICONS is 20px.The background-position of a Sprite image is negative. This means that you move the background image up or left from the upper left corner of the element. For example, if you move the background image 220px to the left, the upper left corner of the element will be facing the upper left corner of the cherry.

Striped background

The stripe background is based on the gradient background.

<div class="bg"></div>
Copy the code
.bg{
  height: 100px;
  width: 200px;
  background: linear-gradient(#fb3,#58a);
}
Copy the code

Bring these two colors closer:

background: linear-gradient(#fb3 20%,#58a 80%);
Copy the code

The top 20% of the div is filled with #fb3 solid, and the bottom 20% is filled with #58a solid. True gradients only occur at 60% of the height of the container.

If both colors are set to 50%, you get a solid color for the evenly divided div background.Because a gradient is an image generated by code, it can be treated like any other background image and can be resized with background-size.

background: linear-gradient(#fb3 50%,#58a 50%);
background-size: 100% 20px;
Copy the code

Since the background is repeatedly tiled by default, the entire container is actually filled with horizontal stripes.You can also create unequal stripes:

background: linear-gradient(#fb3 30%,#58a 30%);
Copy the code

If a color mark position value is smaller than any color mark position value before it in the entire list, the color mark position value is set to the maximum value of all color mark positions that precede it. This means that if we set the position of the second color mark to 0, its position will always be adjusted by the browser to the position of the previous color markCopy the code

We can change the above code to:

background: linear-gradient(#fb3 30%,#58a 0);
Copy the code

To create multicolor stripes:

Background :linear gradient(#fb3 33.3%, #58a 0, #58a 66.6%, yellowgreen 0);Copy the code

Ant border

<div class="ants-border">
   Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laudantium, debitis vel quam tempora ut nisi voluptatibus rem ab. Quas, cum. Itaque, dignissimos! Quos, eos placeat eveniet quasi amet eius officiis!
</div>
Copy the code
.ants-border{ width: 500px; padding: 1em; border: 1px solid transparent; background-image: linear-gradient(white, white), repeating-linear-gradient( -45deg, #000 0%, #000 25%, #fff 0%, #fff 50% ); background-size: 10px 10px; background-clip: padding-box, border-box; animation: ants 10s linear infinite; } @keyframes ants { to { background-position: 100%; }}Copy the code

Drawing steps:

1. Add a black and white striped background to div.

.ants-border{ width: 500px; background-image: repeating-linear-gradient(-45deg, #000 0%, #000 25%, #fff 0%, #fff 50%); background-size: 10px 10px; /* control the width of the stripe */ /* Default background image repeat full screen */}Copy the code

2. Add a white background. When multiple background-images are set on an element, if the positions overlap, the preceding background overwrites the following background. The background is white.

.ants-border{
   ...
   background-image: linear-gradient(white, white),repeating-linear-gradient(-45deg, #000 0%, #000 25%, #fff 0%, #fff 50%); 
   background-size: 10px 10px;
}
Copy the code

3. The background has an attributebackground-clip, the initial value isborder-box, which means the background will be spread all over the border-box.In order to get the striped background out to form the ant border, we put two layers of the backgroundbackground-clipAre set topadding-boxandborder-box.

.ants-border{
   ...
   background-image: linear-gradient(white, white),repeating-linear-gradient(-45deg, #000 0%, #000 25%, #fff 0%, #fff 50%); 
   background-size: 10px 10px;
   background-clip: padding-box, border-box;
}
Copy the code

In this case, the white background is covered with padding-box, and the striped background is covered with border-box. In this case, the white background is still covered, because the range of the two boxes overlaps when the border is not set. So set a 1px border with a transparent color.

.ants-border{
   ...
   border: 1px solid transparent;
}
Copy the code

4. Create moving “ants” by constantly changing the position of the background through animation.

@keyframes ants { to { background-position: 100%; }}Copy the code

Clipping path (clip-path)

Clip-path allows us to crop the element into whatever shape we want.

<img class="pic" src="images/pic7.jpg">
Copy the code

Diamond:

.pic{clip-path: polygon(50% 0,100% 50%,50% 100%,0 50%); }Copy the code

Round:

.pic{
   clip-path: circle(50%);
}
Copy the code

You can also specify SVG as the clipping path:

<img class=" PIC "SRC ="images/pic7.jpg"> <img class=" PIC" SRC ="images/pic7.jpg"> < SVG > <clipPath id="myPath" clipPathUnits="objectBoundingBox"> <path d=" m0.5c" ,0,0.7 0.5, 1, 0,0.3 A 0.25, 0.25, 1,1,1,0.5, 0.3 A, 0.25, 0.25, 1,1,1,1,0.3,0.7 C 1, 0.5, 1,0.5, 1 Z "/ > < / clipPath > < / SVG >Copy the code
.pic{
   clip-path: url(#myPath)
}
Copy the code

CSS cutting paths can use both a percentage value (which is converted to the element’s width and height as the cardinality) and an absolute length value.

pseudo-classes

“CSS uncovered”, talked about a lot of pseudo class coding skills. With pseudo-classes, you can do a lot of clever things with a clean HTML structure.

Parallelogram background

Transform: skewX (degree) transform: skewX (degree) transform: skewX (degree) transform: skewX (degree) transform: skewX (degree) To do this, you can apply all the styles to the pseudo-elements, and then distort the pseudo-elements. Since our content is not contained in pseudo-elements, it is not affected by transfiguration. This applies to any other morphing style and is used when we want to morphing an element without morphing its contents.

<span class="btn">click me</span>
Copy the code
.btn{
   margin: 50px;
   position: relative;
   padding: 10px 20px;
}
.btn:before{
   content: '';
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
   background-color: aqua;
   z-index: -1;
   transform: skewX(-20deg);
}
Copy the code

Speech bubbles

<div class="dialogue"> </div>Copy the code
.dialogue{
   margin-top: 50px;
   padding: 10px;
   border-radius: 2px;;
   display: inline-block;
   position: relative;
   border: 1px solid #ccc;
   max-width: 300px;
   background-color: #fff;
}
.dialogue:before{
   content: '';
   height: 8px;
   width: 8px;
   border: 1px solid;
   border-color: #ccc transparent transparent #ccc;
   background-color: #fff;
   position: absolute;
   top: 15px;
   right: -6px;
   transform: rotate(135deg);
}
Copy the code

Expand the clickable area

For smaller, hard-to-aim controls, expanding the clickable area outward can often improve the user experience, if not the visual size directly.

Pseudo-elements can represent their host elements in response to mouse interactions, so we can overlay a transparent pseudo-element on top of the button and make the pseudo-element 10px larger than the host element in all four directions.

Button {position: relative; /* [other styles] */} button:before {content: "; Position: absolute; Top: - 10 px; Right: - 10 px; Bottom: - 10 px; Left: - 10 px; }Copy the code

With pseudo-elements, we can basically set the clickable region to any size, position, or shape we want, even out of the element’s original position.

Custom check boxes

In order to extend the checkbox’s click range within a form element, we often use a label to correspond to a checkbox. We can hide the checkbox by attaching a style to the label.

<input class="switch" type="checkbox" id="connect" />
<label for="connect"></label>
Copy the code
.switch{/* Hide the checkbox and respond with the label click */ position: Absolute; */ clip: rect(0,0,0,0)}. Switch + label {/* set the label style for the unselected state */ display: inline-block; height: 15px; width: 30px; border-radius: 10px; background-color: #eee; position: relative; }.switch + label:before {/* The slideable little button is label:before pseudo-class */ content: "; display: inline-block; position: absolute; height: 15px; width: 15px; border-radius: 50%; background-color: #fff; right: 0; top: 0; box-shadow: 0 0 2px #666; }. Checked :checked + label {/* Set the label style for the checked state */ background-color: yellowgreen; } .switch:checked + label:before { left: 0; }Copy the code

Similar to: Checked, you can use pseudo-class selectors :hover, : Focus, : Disabled to style check boxes for different states.

Ground glass effect

The frosted glass effect is a blur effect. The key is to blur who? Use of elementsfilter: blur(30px)It will obscure its children, so you can’tclass="content"Element blur; The width and height of the area where the text is located varies, so there is no way to blur it with an empty div and then “pad” it inclass="content"Element. So we came up with pseudo-classes.

<div class="poem"> <div class="content"> <p> <br> Rice flowers in the harvest, <br> listen to the sound of frogs. <br> Seven or eight stars away, two or three points in front of the rain mountain. <br> At the edge of the forest in the old Maodian village, the bridge suddenly appeared when the road turned to the brook. <br> </p> </div> </div>Copy the code

Set the pseudo-class to the same position as the content element, and use negative z-index to move a pseudo-class below the class=”content” element. Be careful when using a negative z-index to move a child element below its parent element: If the parent’s parent element has a background, the child element will appear after them. So set z-index: 1 for class=”content”; Make the pseudo-element appear above the parent element (class=”poem” element).

Set the same background as class=”poem” element for pseudo-elements. In order to overlap the background of pseudo-elements and class=”poem” element, background-attachment: fixed is used. Filter: blur(30px); You get a ground-glass effect.

.poem{ width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; } .poem,.content::before{ background: url('./images/pic9.jpg'); background-size: cover; background-attachment: fixed; } .poem .content{ box-sizing: border-box; color:#f9f9f9; font-size: 20px; The line - height: 2.2 em. letter-spacing: 3px; text-align: center; padding: 40px 30px 35px 40px; Background: hSLA (0, 0%, 100%, 0.3); position: relative; overflow: hidden; z-index: 1; } .poem .content::before{ content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; filter: blur(30px); margin: -30px; z-index: -1; }Copy the code

CSS filter

filter mdn

hsl

To learn CSS filters, you need to learn HSL color models first. You can see this little sister’s video, which is very clear in the color series course.

  • HUE: An attribute of color in which optical transmittance is classified by wavelength. Hue is a solid color without black, white and gray, below is a solid color base wheel.

  • SATURATION, also known as purity, indicates the bright depth of a color.
  • LIGHTNESS: The brightness of a color, which determines its brightness.

On the basis of hue, different color effects can be obtained by adjusting saturation and lightness.

Projection of irregular shape

There is no way to shadow irregular shapes. Like the bubble dialog box.Use filter:drop-shadow to solve this problem.Box-shadow casts a shadow on the entire box element, while drop-shadow only casts a shadow on the opaque part. Take the picture, for example, which is transparent except for the fruit.

The dyeing effect

img{
   height: 100px;
   width: 100px;
   border-radius: 50%;
   filter: sepia() hue-rotate(70deg);
   transition: .5s filter;
}
img:hover{
  filter: none;
}
Copy the code

Weaken the background by blurring

There are many application scenarios of blurred background, such as mobile phone unlocking, website login, QQ music playback page blurred album pictures to be the background.

Simple music playback panel

<div class="main"> <img SRC ="./images/reading.webp" /> <div> <img SRC ="./images/reading.webp" /> <div> </div>Copy the code
.main{ position: relative; display: flex; flex-direction: column; align-items: center; color: #fff; text-align: center; font-size: 20px; line-height: 2em; Background: rgba(0, 0, 0, 0.1); } .main:before{ z-index: -1; content: ''; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: url("./images/reading.webp"); background-size: 100% 100%; The filter: the blur (30 px) opacity (0.6); /* You can't add the filter directly to the.main element. Instead, you can add both the background and the filter to the pseudo-class. Because if a parent element is filtered, all its children will be changed by that filter together. */ } .main img{ height: 160px; width: 160px; border-radius: 50%; margin: 100px 0 50px; animation:rotate 5s linear infinite; } @keyframes rotate { to{ transform: rotate(1turn); }}Copy the code

Interactive picture contrast control

<div class="image-slider"> <img class="gray" src="./images/cat1.jpg"/> <div class="upper-img"> <img src="./images/cat1.jpg"/> <! </div> <input type="range" /> </div>Copy the code
.image-slider { position: relative; display: inline-block; } .image-slider > div { position:absolute; top: 0; left: 0; right: 0; bottom: 0; width: 50%; overflow: hidden; } .image-slider img { display: inline-block; user-select: none; } .image-slider .gray { filter: sepia(); } .image-slider input[type="range"]{ position: absolute; left: 0; bottom: 10px; width: 100%; margin: 0; The filter: contrast (0.5); mix-blend-mode: luminosity; }Copy the code
<script>
   let range = document.querySelector('input[type="range"]'),
       upperImg = document.querySelector('.upper-img')
   range.addEventListener('input', function(ev){
      upperImg.style.width = ev.target.value + '%'
   })
</script>
Copy the code

Text stroke and text glow

The text-shadow property adds one or more shadows to the text.

<div class="hollow">css</div>
<div class="glow">glow</div>
Copy the code
div{ height: 200px; width: 300px; font-size: 100px; text-align: center; } .hollow{ background-color: deeppink; color: #fff; text-shadow: 1px 1px black, 1px -1px black, -1px 1px black, -1px -1px black; */}.glow{background-color: #203; color: #ffc; text-shadow: 0 0 .1em, 0 0 .3em; /* If no color is specified, the shadow will be the same color as the text */}Copy the code

animation

Slow motion, frame by frame — animation-timing-function

Animation: Rotate 5S Linear Infinite, The third parameter linear is the animation timing function animation-timing function, which defines the rhythm of the CSS animation in each animation cycle. More generally, it is the animation speed. For example, Linear, ease-out, ease-in, and ease-in-out are all convenient ways to write, but they are not customized enough. For example, we want an animation that is very fast in the front and 90% of the animation can be done in 10% of the time. You can’t just use these key words.

To make animation speed more DIY, you can usecubic-bezierIt is alsoanimation-timing-functionOne of the,Animation: Rotate 1.5s Cubic - Bezier (.27,1.07,.75,.96) infinite;. Cubic – Bezier curves are called cubic Bezier curves, which are mainly functions of generating velocity curves. The derivation and calculation of this will be a separate article, but we’ll focus on its use.Cubic - the bezier. 27,1.07,. 75,. 96)The parameter accepts four values, which are actually the coordinates of the two control points (red and green handles in the figure below).

By adjusting these two control points, you can adjust the slope of the black Bezier curve, which represents the speed. The slope of the Bezier curve in the figure above is first larger, then smaller, and then larger, and the corresponding animation speed is also first faster, then slower, and then faster.

Adjust bezier curve website, cubic-bezier.com/#.17,.67,.8…

This Bezier time function corresponds to the animation speed which is first fast and then slow, and we use it to write a rotating load animation.The first is theCubic - the bezier. 23,1.21., 81. (94); The second is thelinear; The third is asteps(n).

<span></span>
<span></span>
<span></span>
Copy the code
span{ display: inline-block; height: 30px; width: 30px; border: 2px solid; border-color: transparent lightcoral lightcoral lightcoral; border-radius: 50%; Animation: Rotate 1.5s Cubic - Bezier (.23,1.21,.81,.94) infinite; } span:nth-child(2){ animation-timing-function: linear; } span:nth-child(3){ animation-timing-function: steps(2); } @keyframes rotate { to{ transform: rotate(360deg) } }Copy the code

In addition to the smooth transitions discussed above, there is also the frame-by-frame transition steps(n). In contrast to a smooth transition, steps(n) splits the entire animation into n frames based on the number of steps(n) you specify, and the entire animation is hardcut from frame to frame without any interpolation.

Frame by frame animation combined with Sprite figure is the basis of picture material animation. For example, we can use three pictures to represent the three states of the wings of the bird when it flies, and then continuously switch the three pictures through the frame-by-frame animation to realize the flight of the bird.

<span class="bird"></span>
Copy the code
.bird{ display: inline-block; height: 45px; width: 52px; background: url('./images/birds.png') no-repeat; background-position: -1px; animation: fly .5s steps(3) infinite; } @keyframes fly { 100%{ background-position: -156px; }}Copy the code

Pauseable animation — animation-play-state

Suppose you want to achieve the effect of showing a very long picture, and when the mouse stops over the picture, the picture starts moving, the mouse moves away, the picture stops moving, the mouse moves up again, and the picture starts moving again from where it left off last time.

<div class="window"></div>
Copy the code
.window{ height: 150px; width: 150px; background: url(./images/bg.jpg) no-repeat; background-size: auto 100%; animation: move-pic 10s linear infinite alternate; animation-play-state: paused; /* hover state */}. Window :hover{animation-play-state: running; /*hover state */} @keyframes move-pic {to {background-position: 100% 0; }}Copy the code

Animation delay — animation-delay

Animation-delay specifies the delay before the animation begins.Sometimes you can use this image + water ripple effect to prompt a new message. This can be done with animation-delay:

<div class="wave">
  <img src="./images/cat1.jpg" />
  <span></span>
  <span></span>
</div>
Copy the code
.wave{ position: relative; } .wave img{ height: 50px; width: 50px; border-radius: 50%; } .wave span{ position: absolute; z-index: -1; top: -1px; left: -1px; height: 50px; width: 50px; border-radius: 50%; border: 1px solid orange; animation: 2s wave linear 4; opacity: 0; } .wave span:nth-of-type(2){ animation-delay: 1s; /* keyframes wave {50%{transform: scale(1.2); /* keyframes wave {50%{transform: scale(1.2); opacity: 1; 100%} {the transform: scale (1.4); opacity: 0; }}Copy the code