“CSS Revealed” talks about 47 CSS skills, many of which are not used in daily coding. In addition to listing some practical skills in the book, this paper also tries to help readers understand background, animation and other commonly used but not solid knowledge points. So read this article not only to learn some practical tips, but also to consolidate your CSS basics.

Practical tips

DRY principle

Full name: Don’t Repeat Yourself, this principle applies to all programming languages, not just CSS.

Expand the clickable area

  • Key implementation: pseudo-elements
  • Specific analysis: the use of pseudo elements and positioning to achieve the mouse moved to the edge of the hand shape and clickable
.expand-range {
  position: relative;
}
.expand-range:after {
  content: ' ';
  position: absolute;
  top: -10px; right: -10px; bottom: -10px; left: -10px;
}
Copy the code

SCSS is recommended:

@mixin expand-range($top: -10px, $right: $top.$bottom: $top.$left: $right.$position: relative) {
  position: $position;
  &:after {
    content: ' ';
    position: absolute;
    top: $top;
    right: $right;
    bottom: $bottom;
    left: $left; }}.test {@include expand-range($top: -5px, $position: absolute)}
Copy the code

Use cascading contexts wisely

  • Key implementation: pseudo-element cascading context
  • Concrete analysis: use cascading context andz-index: -1Feature implementation pseudo-element overlay background without blocking text (specific implementation principle referencehere). This is a very common and useful technique that can be used to achieve many unexpected results.address
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  z-index: - 1;
Copy the code

Rounded edges inside the border

  • Key implementation: pseudo-element cascading context
  • Concrete analysis: using pseudo-elements to achieve rounded rectangle and superimposed on the parent element background text above: address

clip-path

  • Key implementation:clip-path
  • Specific analysis: CSS3 new attributesclip-pathRegion clipping can be implemented. There are three functions that browsers now support well:clip-path: circle(50px at 50px 50px)50px 50pxCut a circle with a radius of 50px to the center of the circle.clip-path: ellipse(30px 40px at 50px 50px)50px 50pxCut an ellipse with a transverse radius of 30px and a longitudinal radius of 40px at the center of the circle.clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%)Crop a polygon to multiple coordinates, in this case a diamond. There are theclip-path, you can easily implement any polygon:address

Adaptive ellipses

  • Key implementation:border-radius
  • Specific analysis:border-radiusThe radius of 8 angles can be set up. The horizontal direction (where there is a radian above and below the diagonal) and the vertical direction (where there is a radian around the diagonal) are four, which can be used/Segmentation. If there are fewer than four values specified in the horizontal or vertical directions, and are followedMargin, paddingThe same rules are repeated. If you specify only the horizontal, then the vertical is the same as the horizontal.
    border-radius: 5em 1em; /* equivalent to border-radius: 5em 1em 5em 1em / 5em 1em 5em 1em; * /
Copy the code

Adaptive width

  • Key implementation:min-contentThe keyword
  • Specific analysis: how to implement the width of an element according to the maximum fixed element width of the descendant element? Racking their brains, also can only usedisplay: inline-blockThe package feature implements an incomplete version of:addressThe downside of this approach is that the text is detached from the document flow and the height is not counted in the include block. But if you usemin-contentKeyword, which can be implemented in one line of code with no side effects:address
  width: min-content;
Copy the code

Projection simulates multiple borders

  • Key implementation:box-shadowtheinset
  • Specific analysis: usebox-shadowCan simulate the realization of multiple borders, but because the shadow does not take up space, so can not trigger the click event, the mouse hover border can not appear small hands, so need to cooperateinsetKeywords used:address
  height: 200px;
  background: cyan;
  box-shadow: 0 0 0 5px # 000 inset0 0 0 10px # 555 inset0, 0, 0, 15px # 999 inset;
Copy the code

Unilateral projection

  • Key implementation:box-shadow
  • Specific analysis:box-shadowThe first two parameters specify the x and y offsets of the shadow. Note that if the shadow is positive and the shadow is moving to the right/down, the corresponding left/above part will be left empty (which can be used to hide the blur radius or expand radius). The third parameter is the shadow blur radius, that is, the excessive color added by gaussian blur; The fourth parameter is the shadow extension radius, which indicates the size of the shadow increase, and can be negative, which indicates the size of the shadow decrease:address
  box-shadow: 0. 5px 4px -4px black;
Copy the code

The second parameter make shadow whole down 5 px, the third argument to make shadow around for more than 4 px gaussian blur (note as overall down 5 px, so at this time still no shadow show above), the fourth parameter and narrowed the 4 px, the shadow whole, so both sides didn’t appear fuzzy radius gaussian blur caused by the shadow color, So as to achieve unilateral projection.

You can also set multiple shadow colors separated by commas, such as the following side-drop effect: Address

  box-shadow: 5px 0 5px -5px black.-5px 0 5px -5px black;
Copy the code

Irregular projection

  • Key implementation:filter: drop-shadow()
  • Specific analysis:box-shadowCannot be displayed through transparent background, cannot be displayed over pseudo-elements/child elements, and thesedrop-shadowCan do it. (But any projection will beclip-pathCut out ~ ~)address
  filter: drop-shadow(2px 2px 10px rgba(0, 0,. 5));
Copy the code

Dye and fade effect of filter

Most front-end developers know that the gaussian mode effect of the paste filter is implemented by filter: Blur (), but few of the other color palette effects of the filter are used. filter The values of blur(), dropshadow (), URL (), Brightness (), contrast(), grayscale(), hue-rotate(), invert(), opacity(), saturate(), sepia() ~ ~ yes Use compound forms such as filter: sepia(1) saturate(4), etc. The following is a large set of filter attribute values: address

The pie chart SVG

The CSS implementation of pie charts is very strange, so I ignore it. Recommend using SVG implementation scheme, very simple, first to a basic teaching ~

Let’s draw a circle:

<svg width="100" height="100">
  <circle r="25" cx="50" cy="50" />
</svg>
Copy the code

Here r equals “25” is the radius 25, and cx, cy are the x and y coordinates of the center.

circle {
  fill: yellowgreen;
  stroke: # 666;
  stroke-width: 50;
}
Copy the code

Here we define a stroke of width 40 for the circle:

Set the stroke to a dotted line of length 20 and 10 apart:

circle {
    ...
    stroke-dasharray: 20 10;
}
Copy the code

When the dashed line interval is set to be greater than or equal to the circle, the length of the dashed line segment is a sector area (when the line segment length is equal to the circle, the sector reaches 100%) :

Give SVG rounded corners and a background color and rotate -90deg to achieve a pie chart: Address (use the currentColor keyword and color: Inherit to implement the DRY principle).

However, the sector size of such pie chart is not easy to calculate. To facilitate calculation, the length of the dotted line segment can also be infinitely close to 100 in the circle, so that the percentage of sectors can be set more conveniently. The circle is 2 PI r, so 100 is 2 PI r, and the radius r is approximated to 16. Using the viewBox attribute of SVG, the pie chart of adaptive container size: address is realized

The downside of this approach is that when you set stroke-dasharray: 100, 100 will have a slit, which is unavoidable for approximations.

backgroundbackground

Background is one of the most commonly used attributes, but as an old front end, I’m ashamed to say THAT I don’t have a complete grasp of it yet.

Background is a shorthand property that can include multiple properties: Background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-siz E, background – attachment. Let’s take a look at each of these attributes in action:

  • background-colorThe most commonly used attribute, not inherited by default (backgroundIs not inherited by default), the initial value istransparent; Sometimes you can use default inheritance for fun effects, such as reflections;
  • backgroundo-imageBackground image, can be separated by commas set multiple, can be the image URL or gradient;
  • background-clipBackground clipping, can be comma separated set multiple, value can bebroder-box(Initial value),padding-box,content-box,text(New, will be the background text clipped);
  • background-originSets the relative area of the background starting point, collocatedbackground-positionCan be separated by commas. The value can beborder-box,padding-box(Initial value),content-box;
  • background-positionSets the starting point of the background. Multiple values can be separated by commas10px 20pxcenter centerleft 10px bottom 20pxAnd so on, very flexible;
  • background-sizeSet the size of the background. Multiple values can be separated by commas and numeric values such as30px 40px,auto auto(Initial value),conver,contain;background-repeat: repeatIt is repeated according to this size.
  • background-repeatSets how the background repeats, starting withrepeatValues are also commonly usedno-repeat;
  • background-attachmentSets whether the position of the background image is fixed in the viewport or scrolls along the block containing it. Multiple values can be set comma separatedscroll(Initial value),local,fixed. Details seeMDN

Background-size can only be followed by background-position, for example, “center / 80%”.

Translucent border

  • Key implementation:background-clip
  • Specific analysis: becausebackgroundProperty overwrites the entire box model by default, including the borderborder, so setborder-color: rgba(0, 0, 0, .5)Will show the background color, not translucent border effect. CSS 3 increasedbackground-clipProperty that defines the clipping area for the background fill. Set up thepadding-boxTranslucent borders can be achieved:address
  border: 10px solid rgba(255, 255, 255, . 5);
  background: white;
  background-clip: padding-box;
Copy the code

Flexible background positioning

  • Key implementation:backgrond-position background-origin
  • We all knowbackground-positionYou can position the background image and so on, but it’s all relativepadding-boxAt the top left corner. Css3 allows you to write:background-position: right 10px bottom 20pxAnd CSS3 also supportsbackground-origin, its default value is as good as its performanceborder-box, can be set topadding-boxandcontent-box:address
  height: 200px;
  padding: 10px;
  border: 5px solid cyan;
  background: lightblue;
  background: radial-gradient(#00a4fd, cyan) no-repeat right 100px bottom / 100px 100px;
  background-origin: content-box;
Copy the code

Setting background-position to a percentage value is tricky. The percentage value actually performs the following calculation formula:

(container width - image width) * (position x%) = (x offset value)
(container height - image height) * (position y%) = (y offset value)
Copy the code

According to the calculation formula, when the value is 0%, the actual offset value is 0px, and the left boundary (or upper boundary) of the image coincides with the left boundary (or upper boundary) of the container. When the value is 50%, the actual offset value is half of the container minus the remaining space of the image, the left and right boundaries of the image (or upper and lower boundaries) are equal to the left and right boundaries of the container (or upper and lower boundaries), and the midpoint of the image and the container coincide. When the value is 100%, the actual offset is the container minus the remaining space of the image, so the right (or bottom) edge of the image coincides with the right (or bottom) edge of the container. The difference between the two is also valid when it is negative. address

Striped background

  • Key implementation:background-image
  • Implementation analysis: the use of linear gradient to achieve a variety of color staggered repetition, the formation of stripe background.lienar-gradientThe first parameter of the gradient is the Angle, which can be the direction keywordto top(initial value, can be ignored), etc., can also be an Angle90degAnd so on;#fb3 50%Refers to the color code and the end position value; herelinear-gradientThe second position value of 0 is resolved to the position value of the previous color, which is 50%DRYThe principle.
background: linear-gradient(#fb3 50%, #58a 0);
background-size: 100% 30px;
Copy the code

Can also be set to a vertical stripe background:

background: linear-gradient(to right.#fb3 50%, #58a 0);
background-size: 100% 30px;
Copy the code

Can also be set to diagonal stripe:

background: linear-gradient(45deg.#fb3 25%, #58a 0, #58a 50%, #fb3 0, #fb3 75%, #58a 0);
background-size: 30px 30px;
Copy the code

Diagonal stripes need to be set up with four stripes to achieve seamless stitching in tiling.

Better diagonal stripe :(here the starting value #fb3 0 must be set)

background: repeating-linear-gradient(60deg.#fb3 0, #fb3 15px.#58a 0, #58a 30px);
Copy the code

The grid

  • Key implementation:background-image,background-size
  • Multiple gradients can be set to different directions and sizes to achieve a grid effect. address
background: #58a;
background-image: linear-gradient(white 1px.transparent 0),
                  linear-gradient(to right.white 1px.transparent 0);
background-size: 30px 30px;
Copy the code

Better grid:

background: #58a;
background-image: linear-gradient(white 2px.transparent 0),
                  linear-gradient(to right.white 2px.transparent 0),
                  linear-gradient(rgba(255, 255, 255, . 51)px.transparent 0),
                  linear-gradient(to right.rgba(255, 255, 255, . 51)px.transparent 0);
background-size: 75px 75px, 75,px 75px, 15px 15px, 15px 15px;
Copy the code

The board

  • Key implementation:background-image,background-size,background-position
  • Specific analysis: set different sizes and positions for multiple gradients, you can achieve the effect of grid. address
  background: #eee;
  background-image:
    linear-gradient(45deg.rgba(0, 0, 0, 25.25%),transparent 0, transparent 75%, rgba(0, 0, 0, 25.) 0),
    linear-gradient(45deg.rgba(0, 0, 0, 25.25%),transparent 0, transparent 75%, rgba(0, 0, 0, 25.) 0);
  background-size: 30px 30px;
  background-position: 0 0, 15px 15px;
Copy the code

Angle

  • Key implementation: linear gradient
  • Specific analysis: 150deg is to form a 30 degree Angle, convenient use of Pythagorean theorem to measure various lengths, the rest depends on your own ~ address

The background property is basically covered here, just look useless, more hands-on practice.

Wave point

  • Key implementation: radial gradient
  • Specific analysis: the use of radial gradient to achieve a small dot, according to the regular placement can generate the address of the wave point
  background:
    radial-gradient(tan 30%, transparent 0),
    radial-gradient(tan 30%, transparent 0);
  background-color: # 666;
  background-size: 30px 30px;
  background-position: 0 0, 15px 15px;
Copy the code

Corner cut

  • Key implementation:clip-path, radial gradient
  • Specific analysis: generally speaking, polygon cutting effect (in fact, or irregular polygon) withclip-pathBoth can be easily implemented, but for circular cuts, a radial gradient is the best choice. But what if you have a curved cut?radial-linearThe first parameter specifies the starting point of the gradient (center by default) and whether the gradient type is oval or round.address
  background:
    radial-gradient(circle at top left.transparent 15px.blue 0) top left.radial-gradient(circle at top right.transparent 15px.cyan 0) top right.radial-gradient(circle at bottom right.transparent 15px.cyan 0) bottom right.radial-gradient(circle at bottom left.transparent 15px.cyan 0) bottom left;
  background-size: 50% 50%;
  background-repeat: no-repeat;
Copy the code

The pie chart

  • Key implementation: tapered gradient
  • Concrete analysis: It’s easy to implement multiple sectors with tapered gradients, so the SVG approach is a good learning curve for SVG usage.
  background: conic-gradient(lightblue 30%, yellowgreen 0, yellowgreen 50%, cyan 0);
Copy the code

animationanimation

Animation properties are animation-name, animation-duration, Animation-timing-function, animation-delay, animation-rotund-count, animation-direction, animation-fill-mode, animation-pl A shorthand form of the ay-state property.

  • animation-nameSpecify the name of the animation, which can be separated by commas.
  • animation-durationSpecify when the animation runs.
  • animation-delaySpecifies the delay before animation execution.
  • animation-timing-functionSpecifies the speed function at which the animation executes, as inlinear,ease(Default),ease-in-outEtc. Bessel functions can also be usedcubic-bezier();
  • animation-iteration-countSpecifies the number of times the animation runs. Default is 1InfiniteInfinite time;
  • animation-directionSpecifies whether the animation is played backwards,normalThe normal order,alternateAlternate running,reverseRun in reverse,alternate-reverseReverse alternating operation;
  • animation-fill-modeSet the style of the CSS animation before and after execution,noneDon’t set,forwardsKeep the style of the last frame,backwardsApply the value defined in the first keyframe immediately and retain it for the duration of animation-delay,bothAt the same time the applicationforwardsandbackwardsThe rules;
  • animation-play-stateDefines whether an animation runs or pauses, with a value ofrunning,paused.

The springback effect

How do you add a rebound effect to an animation? Here’s one of the most convenient ways:

  • Key implementation:cubic-bezier(x1, y1, x2, y2)
  • Specific analysis: using the second control anchor point of Bessel curve is greater than 1 to achieve springback

The horizontal axis is time, and the vertical axis is animation progress. The Bezier curve in the figure has two control handles, x1 and y1 control the first anchor point, x2 and y2 control the second anchor point. X1 and x2 cannot be greater than or less than 1, but y1 and y2 can. When y2 is greater than 1, you have the effect of getting to the end point early, then passing the end point, and then coming back, like a rebound. address

  animation: bounce 3s both cubic-bezier(7..1..3., 2);
Copy the code

The transition property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. Use Transition to do the same thing: address

p {
  transform-origin: 1.4 em -.4em;
  transition: transform .5s cubic-bezier(.25, .1, .3, 1.5);
}

input:not(:focus) + p {
  transform: scale(0);
  transition: transform 300ms; /* Resets transition-timing-function when zooming out. */
}
Copy the code

Moving background

  • Key implementation:animation,background-position
  • Specific analysis: will animate the last framebackground-positionSet to100% 0%, the animation will change the background position from the original0% 0%To the last100% 0%Too much:address
div {
  width: 150px; height: 150px;
  background: url('http://c3.staticflickr.com/3/2671/3904743709_74bc76d5ac_b.jpg');
  background-size: auto 100%;	
  animation: panoramic 10s linear infinite alternate;
}
div:hover {
  animation-play-state: paused;
}

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

Animation of circular path movement

  • Key implementation:animation transform-origin
  • Specific analysis: set the rotating containertransform-originIs the center point of the large circle container, and the principle that the rotation angles of the two elements cancel each other when they rotate in different directions is used to realize the rotation of the image along the circular path while keeping its own Angle unchanged. Notice that the distance between the smaller circle and the larger circle is from the larger circlepaddingAttribute control, adjustmentpaddingNeed to adjust the rotation origin of the small circletransform-originTo keep the loop path correct:address
@keyframes spin {
  to { transform: rotate(1turn); }}.avatar {
  animation: spin 3s linear 2s infinite;
  transform-origin: 110px 110px;
}
.avatar > img {
  animation: inherit;
  animation-direction: reverse;
}
Copy the code

I recommend CSS articles

In fact, there is no lack of good articles on CSS techniques in the community, here are a few I think written excellent CSS techniques article (of course, you may also read, I am ashamed of the fact that I have not finished reading) :

  • Beyond the CSS
  • Use CSS development techniques flexibly
  • Front-end foundation of the CSS world (or shamefully added, but I also collect, often will see, really feel very valuable: for the CSS system has not learned the students)
  • 49 CSS facts you may not know
  • CSS You May not Know (Season 2)
  • Practical tips from CSS World
  • I write a common routine for CSS
  • 50 Basic CSS Interview Questions (with answers)
  • Summary of CSS interview questions

conclusion

Overall, CSS Inside Out didn’t surprise me much, and I personally didn’t get as much out of it as I did with CSS World. Of course, this book is purely technical and doesn’t tell much about principles, so it can’t be criticized. Interested students can follow me to learn a wave of CSS world, I believe there will be greater harvest ~