“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Special statement: The original is not easy, shall not be reproduced without authorization or plagiarism, if you need to reprint can contact the author authorization

preface

I’ve published an article called “Use CSS Variables to Make Your CSS More exciting” and devoted all of it to CSS variables. Variables are one of the most powerful features of CSS, and as browsers become more sophisticated, they can be used in a wide range of projects, with no concern for compatibility.

While variables can play a leading role in pure CSS, they were originally designed to facilitate the connection between CSS and JS. The CSS uses variables to have the following benefits.

  • Reduce repetition of style code
  • Increase the extensibility of style codes
  • Increase the flexibility of your style code
  • Add a communication mode between CSS and JS
  • Change a style without traversing the DOM deeply

The topic of this article is to combine another feature called calc() to do more, mainly to simplify the effect of JS-BASED logic based on variables communicating with JS. For more details on CSS variables, see CSS Variables to Make Your CSS more exciting.

In order to let everyone feel the perfect fit between variables and calc(), the author designed a magnifying glass effect to show the charm of its collocation.

Dynamic calculation

Calc () is a dynamic unit of calculation. Values, lengths, angles, times, and percentages can be used as parameters. By performing a mathematical expression and returning the calculated value after the operation, you can reduce the amount of manual computation or even eliminate the need for manual computation.

Calc () is hungry, all units of measurement can be used as parameters to participate in the whole dynamic calculation.

  • The numerical:The integer,Floating point Numbers
  • The length of the:px,em,rem,vw,vhEtc.
  • The Angle:deg,turn
  • time:s,ms
  • The percentage:%

Although calc() is easy to use, but the novice will inevitably encounter some pits, remember the following characteristics, I believe you can play with calc().

  • Four operations: only usable+,-,*,/As an operational symbol
  • Operation order: follow the operation order of addition, subtraction, multiplication and division, available(a)Upgrade operation level
  • Symbolic link: Each operator symbol must be usedThe blank spaceInterval up
  • Mixed calculation: dynamic calculation with different measurement units can be mixed

The third is particularly important. If you fail to comply, the browser simply ignores this property.

Have you ever encountered the left or right jitter of the page route in the jump process because of the scroll bar or no scroll bar in SPA? This makes the ocD patient very uncomfortable, at this time can use calc() cleverly to solve the problem.

.elem {
    padding-right: calc(100vw - 100%);
}
Copy the code

You don’t declare padding-right as the scrollbar width directly because the default scrollbar width can be different for each browser. 100VW is the window width and 100% of the content width, so 100VW-100% is the scrollbar width. Declare padding-right to keep the scrollbar in place, so the page will not shake if the scrollbar appears.

On the other hand, in mobile development, you can kill all mobile scaling schemes with a single line of CSS code, regardless of the compatibility of earlier browsers.

/* based on the UI width=750px DPR=2 page */
html {
    font-size: calc(100vw / 7.5);
}
Copy the code

< HTML > < span style = “box-sizing: border-box; color: RGB (74, 74, 74); font-size: 100/750 = x/100vw

A magnifying glass

The traditional magnifying glass effect relies on most OF the JS logic, the movement and display effects are dependent on JS, through JS calculate the offset to render the style.

The variable is used to simplify these JS logic, and the logic of calculating offset is integrated into the variable. Calc () is used for dynamic computing unit, which is the core usage of this transformation.

Based on the above requirements, the left and up offset of the mouse can be obtained in real time, and these two offsets are relative to the parent node. By combining the left and upper offsets with calc(), the display position of the magnifying glass display content relative to the parent node can be calculated.

Event provides the following eight offsets, which can be confusing if you don’t understand their concept.

  • screenX/screenYRelative:Upper left corner of screen areaLocation, if rolling behavior occurs, relative to the region location
  • pageX/pageYRelative:Top left corner of the page areapositioning
  • clientX/clientYRelative:Top left corner of the browser viewable areapositioning
  • offsetX/offsetYRelative:Upper left corner of the parent node areaLocate, relative if there is no parent node<html>or<body>positioning

Listing these offset concepts, offsetX/offsetY was found to be the most suitable, so use it as a magnifying glass to show where the content is displayed relative to the parent node.

<div class="magnifier" id="magnifier"></div>
Copy the code
document.getElementById("magnifier").addEventListener("mousemove".e= > {
    e.target.style.setProperty("--x".`${e.offsetX}px`);
    e.target.style.setProperty("--y".`${e.offsetY}px`);
});
Copy the code

Next, use sass to build the magnifying glass effect. The magnifying glass display is actually to magnify the original image N times, and intercept the content in a certain area according to the proportion of the above offset.

First define the relevant Sass variables. If the magnification is set to 2 times, the width and height of the enlarged image will also be 2 times the original width and height. Declare two variables, divided into –x and –y.

The background of the author’s favorite guangzhou Pearl River New City CBD family photo, do not like to replace the background ha!

$ratio: 2;
$box-w: 600px;
$box-h: 400px;
$box-bg: "https://static.yangzw.vip/codepen/gz.jpg";
$outbox-w: $box-w * $ratio;
$outbox-h: $box-h * $ratio;
.magnifier {
    --x: 0;
    --y: 0;
    overflow: hidden;
    position: relative;
    width: $box-w;
    height: $box-h;
    background: url($box-bg) no-repeat center/100% 100%;
    cursor: pointer;
}
Copy the code

In this scenario it is obvious that there is no need to insert a child node as a container for the magnifying glass. Instead, use ::before.

The magnifying glass is 100px wide and 0px wide when in use and 0px when not in use. The center of the magnifying glass aligns with the mouse cursor by absolutely positioning the magnifying glass as it moves with the mouse, declaring left and top, and filling in the center of the magnifying glass by declaring Transform :translate(-50%,-50%). Since the left and top positions the magnifying glass, you also need to declare will-change to improve the performance problems caused by the left and top changes.

.magnifier{&::before {
        --size: 0;
        position: absolute;
        left: var(--x);
        top: var(--y);
        border-radius: 100%;
        width: var(--size);
        height: var(--size);
        box-shadow: 1px 1px 3px rgba(# 000.5);
        content: "";
        will-change: left, top;
        transform: translate(-50%, -50%);
    }
    &:hover::before {
        --size: 100px; }}Copy the code

Next, use background to display the magnifying glass. $outbox-w $outbox-h $outbox-h $outbox-h $outbox-h $outbox-w $outbox-h Background :#333 URL ($box-bg) no-repeat $scale-x $scale-y/$outbox-w $outbox-h, $scale-x and $scale-y correspond to position-x and position-y, which are used to change the background position as the mouse moves.

Horizontal offset = offsetX * magnifying glass width/magnifying glass Vertical offset = offsetY * magnifying glass height/magnifying glassCopy the code

Based on the background-position positive and negative value problem, the above two formulas need to be multiplied by -1 to become the following formula.

Horizontal offset = width/magnifying glass - offsetX * magnifying glass Vertical offset = height/magnifying glass - offsetY * magnifying glassCopy the code

$scale-x (); $scale-y ();

$scale-x: calc(var(--size) / #{$ratio# {} -$ratio} * var(--x));
$scale-y: calc(var(--size) / #{$ratio# {} -$ratio} * var(--y));
Copy the code

The final SCSS file is as follows.

$ratio: 2;
$box-w: 600px;
$box-h: 400px;
$box-bg: "https://static.yangzw.vip/codepen/gz.jpg";
$outbox-w: $box-w * $ratio;
$outbox-h: $box-h * $ratio;
.magnifier {
    --x: 0;
    --y: 0;
    overflow: hidden;
    position: relative;
    width: $box-w;
    height: $box-h;
    background: url($box-bg) no-repeat center/100% 100%;
    cursor: pointer;
    &::before {
        --size: 0;
        $scale-x: calc(var(--size) / #{$ratio# {} -$ratio} * var(--x));
        $scale-y: calc(var(--size) / #{$ratio# {} -$ratio} * var(--y));
        position: absolute;
        left: var(--x);
        top: var(--y);
        border-radius: 100%;
        width: var(--size);
        height: var(--size);
        background: # 333 url($box-bg) no-repeat $scale-x $scale-y/$outbox-w $outbox-h;
        box-shadow: 1px 1px 3px rgba(# 000.5);
        content: "";
        will-change: left, top;
        transform: translate(-50%, -50%);
    }
    &:hover::before {
        --size: 100px; }}Copy the code

  • Online demo:Here
  • Online source code:Here

conclusion

Little variables can play with calc() the same way, and there are many more CSS tricks to be discovered.

Many students may think CSS is very simple, but the real play can also be compared with JS. The author is engaged in the front-end field for many years, has been committed to the research and application of CSS technology, of course, really not to play, but in the process of playing to practice the knowledge fully applied to the work.

JS is important but CSS is equally important, I hope that the students like CSS pay more attention to the author, I believe that you will have more CSS harvest. When you are not willing to learn CSS, please browse the following sites, I believe you will have a different experience.

  • Personal website: Temporary supportPCBrowse, reject supportIExplorer
  • Special album: Temporary supportPCBrowse, reject supportIExplorerTo view the source code, please stampHere,

More of my CSS development experience has been written into the mining volume “Playing with the Art of CSS”, which is a small volume and the only one on CSS in the mining community. I believe that you who care about CSS will love it. I have applied for 100 copies of the booklet to sister 60 % discount code OGecoefC, like CSS students can understand the next oh.

The author has expected to read more than ten thousand nuggets

  • 15,000 words to summarize all the features of ES6:16.8 w.Reading,4600 +Thumb up quantity
  • Use CSS development skills flexibly:14.1 w.Reading,4600 +Thumb up quantity
  • Senior front-end H5 pit must pay attention to article 40 of the mobile end guide | netease three years practice:6.1 w.Reading,3800 +Thumb up quantity
  • Flexible use of JS development skills:5.5 w.Reading,1700 +Thumb up quantity
  • To senior front-end on performance optimization of the nine main strategy and six indicators | netease practice for four years:3.2 w.Reading,1900 +Thumb up quantity
  • 25 Advanced Uses of Array Reduce you Need to know:3.1 w.Reading,1000 +Thumb up quantity
  • Eight hardcore skills take you rapidly improve CSS technology | Denver live summary:2.1 w.Reading,800 +Thumb up quantity
  • Use CSS variables to make your CSS more exciting:1.9 w.Reading,600 +Thumb up quantity
  • A key formatting code brings pleasure | you’re still in for each project configuration Stylelint and Eslint:1.1 w.Reading,200 +Thumb up quantity
  • Determine the browser operating environment in detail:1.1 w.Reading,200 +Thumb up quantity
  • Super 8 is not necessarily know and practical pure CSS layout and typesetting skills | netease in four years’ practice:1.1 w.Reading,400 +Thumb up quantity

conclusion

❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create more high-quality articles

Follow public AccountIQ front-end, a focus on CSS/JS development skills of the front-end public number, more front-end small dry goods waiting for you oh

  • Follow and replydataFree access to study materials
  • Follow and replyInto the group ofPull you into the tech group
  • Welcome to attentionIQ front-endAnd moreCSS/JS development skillsOnly in the public account push