Тёмный

calc() lets you do some real CSS magic 

Kevin Powell
Подписаться 907 тыс.
Просмотров 179 тыс.
50% 1

Start creating responsive layouts with confidence with my free responsive layouts course: courses.kevinpowell.co/conque...
CSS calc() allows us to do math in CSS but it doesn't always have the most obvious use cases. A lot of the time it's super helpful in more sneaky kinds of ways. In this video, I look at how it compares to doing math in a preprocessor as well as a few fun use cases for it where it does some really fun things!
Cloud Four Article by Tyler Sticka that I mention - cloudfour.com/thinks/breaking...
---
Come and hangout, ask questions, suggest ideas, and meet some awesome people over in The Community: / discord
I have a newsletter! www.kevinpowell.co/newsletter
New to Sass, or want to step up your game with it? I've got a course just for you: www.kevinpowell.co/learn-sass
---
My Code Editor: VS Code - code.visualstudio.com/
How my browser refreshes when I save: • How to automatically r...
---
Support me on Patreon: / kevinpowell
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my RU-vid channel, make sure to follow me on Instagram and Twitter.
Instagram: / kevinpowell.co
Twitter: / kevinjpowell
Codepen: codepen.io/kevinpowell/
Github: github.com/kevin-powell

Опубликовано:

 

17 май 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 216   
@biomcanx1
@biomcanx1 5 лет назад
Awesome thanks! The only thing I would add is how important the spaces around the ' + ' are in the calc. It will not perform a calculation if they are not there. Everyone else may know this already, but it bit me for a little bit trying to figure it out.
@KevinPowell
@KevinPowell 5 лет назад
Good point Gene, I probably should have talked a bit more about the very basics of it right off the top before diving in deeper.
@franktielemans6624
@franktielemans6624 5 лет назад
@Gene Price that's right, you can't also have a space between the calc function and first opening bracket. @@KevinPowell Did you ever experiment with calc and CSS variables? I tried to and it seems that you can define variables to a calculation but you can't calc with the variables. At least I don't know how.
@kolklik
@kolklik 5 лет назад
@@franktielemans6624 Sure you can calc with variables/custom properties. jsfiddle.net/aLs8zv5h/
@ynnoz4452
@ynnoz4452 5 лет назад
My favorite calc() trick is this one : html{ margin-left: calc(100vw - 100%); } It removes the "windows jumping" when a scrollbar on the right pops in or out. Perfect for variable/interactive layouts.
@kuranam
@kuranam 2 года назад
How could I use Calc, to preserve the height and width of a image. I am making an ePub, and the picture pass to another Page and it show clipped.
@pineapplerindm
@pineapplerindm 8 месяцев назад
@@kuranam 2 years late but you don't need calc - you can use `aspect-ratio` (or `object-fit: contain`, though that won't change the height/width, it'll only keep the image undistorted)
@thehigherman9918
@thehigherman9918 5 лет назад
The video is about calc(), But I also learned about viewport and vh and vw. This really saved a website I had to restore.
@YungSchmutz
@YungSchmutz 5 лет назад
Samesies
@badihbarakat5832
@badihbarakat5832 5 лет назад
I learned a couple of new css attributes I didn't know about. I didn't even know I can hide the scroll bars without affecting the flow of the contents...
@jenstornell
@jenstornell 5 лет назад
That's an awesome trick. I tested it today and even made it fluid. It may look hackish but it works as expected now. `--wrap-padding: calc( 32px + (128 - 32) * (100vw - (var(--min-width) * 1px)) / (var(--max-width) - var(--min-width)) ); width: calc(100vw - var(--wrap-padding) - 17px); max-width: 1200px; margin: 0 auto; @media screen and (max-width: 320px) { width: calc(100vw - 2rem - 17px); } @media screen and (min-width: 1200px) { width: calc(100vw - 8rem); }`
@jmerino06
@jmerino06 4 года назад
I have been coding websites for almost 20 years. watching your videos reminds me i have a lot to learn. thank you for the time, skills and know how you share on every video.
@milleniummoses
@milleniummoses 5 лет назад
Not only do I have a better understanding of how calc works, but you also answered my (unasked) question about making headline text responsive without so media queries.
@mr.webdev3700
@mr.webdev3700 5 лет назад
The calc() function is really awesome indeed! Great tutorial Kevin! 👍👍👍👍👍👍👍👍👍👍
@crooker2
@crooker2 5 лет назад
That breakout div is great for creating dynamic content. I build cms sites for clients, but the content they enter is always contained in a bootstrap container. This gives me the option of allowing clients to build their own wide block WITHOUT having to break out of the container and re-instating it. Great tip! Thanks, Kev!
@boombaby1769
@boombaby1769 5 лет назад
Awesome! I've been working with CSS for quite a while now, but this feature was completely off my radar. This will be VERY useful for me, thank you!
@MoeBass
@MoeBass 5 лет назад
I was introduced to object-fit with this video, and the break out of container technique was clever!
@GnomePuntTrainerYT
@GnomePuntTrainerYT 5 лет назад
The break out container technique is mindblowing to me. I won't have to wrap a div or section or something around the text that I'd like to give a background for.
@120tonns
@120tonns 5 лет назад
developer.mozilla.org/en-US/docs/Web/CSS/object-fit
@violet-trash
@violet-trash 2 года назад
Object-fix is amazing, I can't believe I spent so long making divs with image backgrounds like a sucker.
@bruhcsp
@bruhcsp 5 лет назад
Perfect!!! I loved what you did with the font-size!
@busyrand
@busyrand 5 лет назад
Very nice tutorial. First time I've ever seen a clear practical use for the calc function.
@novachi09
@novachi09 5 лет назад
This is sooo helpful, honestly. I didn't even look specifically for this but I'm glad it poped up in my recommended section
@AdolfoBarreto75
@AdolfoBarreto75 5 лет назад
Yes! I've been waiting for this one. THANK YOU! Haven't watched it yet but I know it will be good!
@moy2010
@moy2010 5 лет назад
To prevent the horizontal scrolling issue, I do the following with css calc: calc(100% + calc(100vw - 100%))
@KevinPowell
@KevinPowell 5 лет назад
Hrm, never would have thought of that, cool :)
@stepanostapuk4120
@stepanostapuk4120 5 лет назад
Calc in Calc bad work for IE and Safari
@radoslawzielinski9016
@radoslawzielinski9016 4 года назад
which rule do you apply that to please?
@franktielemans6624
@franktielemans6624 4 года назад
@@radoslawzielinski9016 to the html element or body element i guess
@Tryanide
@Tryanide 5 лет назад
Calc is great in many places, but sometimes there's simpler solutions. In the case of the big-image, instead of using a "complicated" calc(-50vw + 50%) (which is, arguably, difficult to understand, especially for newcomers), simply use margin: 0 -3em instead. This will also pull the image 3em to the left and 3em to the right (the combined 6em you subtract from your container). One thing to keep in mind when using techniques like these or when working with EM units in general: local font-size changes on an element will override the EM size inherited from parents. If possible, try to make your lives easier by using REM whenever you can.
@laht93
@laht93 5 лет назад
Using calc(-50vw + 50%) does have the advantage of working within any parent container, no matter the width. You could make it a class to put on things, (almost) regardless of context.
@sonydroid2253
@sonydroid2253 4 года назад
Kevin, I want to take this time and opportunity to say a genuine heartfelt thank. Sharing your passion on RU-vid is helping me understand how the modern web is built. My sites are responsive with a modern stylish feel now. I even have confidence to secure paid work now. X
@JohnMcCormack
@JohnMcCormack 5 лет назад
Really nicely explained, Kevin. Thank you!
@PeggyOConnor1946
@PeggyOConnor1946 5 лет назад
You are a talented master teacher. Kudos. This tip was useful to me immediately.
@techscoville
@techscoville 4 года назад
Really awesome, I remember trying the calc( ) function, it was tricky, but it now clear and simple
@5tevend
@5tevend 3 года назад
I work for an event app / event website company and we have a left-sidenav that displays on desktop by default with a width of 320px, that can collapse to being around 60px wide. sometimes i need to create a square container so i often find myself using calc functions, or wrapping calcs for max-widths, i had a client the other week who didn't like how when the left-sidenav was collapsed things flexed and stretched, so another useful trick there was width:calc(100vw - 320px); and then wrap that calc function in another calc such as width:calc( calc(100vw - 320px) / 2); so if i have a container with specific info/ a cta it doesn't flex at any point, i can then set it's max width as well so i have this fixed point for larger screen sizes, which if you want to save time could also be made into a css-variable for easier use so you can have --widget-width:calc(100vw - 320px); and use it in the realms of width:calc(--widget-width / 2) or 3 or 4 or etc; and a max width of lets say 1200px, although in this example this is only really used in a media query for min-width tablet and onwards i've found some use to it, especially if you need to make scalable square pieces, then you can do @media(orientation:landscape) { div { width:calc(100vh - 2em); } } and for portrait width:calc(100vw - 2em);
@danielelgressy
@danielelgressy 4 года назад
very calm and accurate explanation :) really like your videos , short ,and professional
@briankgarland
@briankgarland 3 года назад
I been looking everywhere for these very examples. Thanks!
@philmyglass877
@philmyglass877 4 года назад
This is brilliant, another tool in the belt. Thanks so much!
@leogarza5022
@leogarza5022 5 лет назад
This was very informative! Thank you for sharing!
@jamesrosemary2932
@jamesrosemary2932 5 лет назад
How could I have been living my life without this?
@jovaniedelacruz
@jovaniedelacruz 5 лет назад
Subscribed! That vw and break out container image is super cool
@erezspeiser4976
@erezspeiser4976 4 года назад
Awesome video. I stumbled upon it by accident and it solved a problem I had for a long time and thought it could not be solved. Thanks! Great channel!
@drewbird87
@drewbird87 5 лет назад
Thank you for giving me something new to love!
@Griesinho
@Griesinho 5 лет назад
Thx so much for this tutorial... and your other ones as well 🤘
@MisterMajister
@MisterMajister 5 лет назад
THANK YOU! Just made my image gallery so much easier to handle. Now I can simply mix padding in px's to my img-width in percentage: width:calc(50% - 12px); since I have a 6px padding on each side. Looks exactly as I want it to!
@Kozi03
@Kozi03 Год назад
Life changing for images and headings!
@badihbarakat5832
@badihbarakat5832 5 лет назад
Ur the best, Kevin... I've learnt a long more from this video than just the calc()... Many thanks... 😁
@brunoliveiralcantara
@brunoliveiralcantara 5 лет назад
Really good function. Congratulations on your video!
@RockstahRolln
@RockstahRolln 5 лет назад
This is Terrific!! Thank You!
@soultouchingsongs
@soultouchingsongs 5 лет назад
Awesome video.. that container close and open was a bit too much.. now got a solution with this video. Thanks a million!
@noelabey
@noelabey 5 лет назад
5:00 forward the fun starts. I subscribed and hit that bell
@mkmalikcom
@mkmalikcom 5 лет назад
wow.... loved it you are great
@alinisar87
@alinisar87 5 лет назад
Hey Kevin, great video. I have a question (not related to calc though), what do you think of using % units (e.g. font-size: 140%; ) for setting fonts of different elements, after setting main font in html selector as font-size: 16px?
@Valky1954
@Valky1954 5 лет назад
Thanks for this, learned something new :)
@nonchalant8473
@nonchalant8473 5 лет назад
Great tutorial. Thanks!
@mohan9285
@mohan9285 4 года назад
Awesome :) I normally use calc() for calculating the height of a container/div and give overflow-y: auto for getting scroll. It helps me in calculating dynamically according to the other content on the page. In your video, I liked the way how we can get the section out from container and styling those. pretty cool.
@fluntimes
@fluntimes 3 года назад
I can definitely see myself using that full width thing. The alternative is to make a whole bunch of divs that are full width with an inner to constrain content when necessary. Calc() rocks!
@OutOfNameIdeas2
@OutOfNameIdeas2 5 лет назад
Shared and liked! Thank you for sharing this!!!
@sashikantanayak6354
@sashikantanayak6354 3 года назад
Very good Kevin, Thank you!
@Zefrem23
@Zefrem23 5 лет назад
The, er, hidden gem here is the 'overflow-x:hidden' to sort out the 100vw issue, which is going to fix some mobile SEO issues on a couple of client's sites for sure. Thanks for this video!
@Max_Griswald
@Max_Griswald 5 лет назад
My god, this was such a lifesaver for me...
@fragrantbloom
@fragrantbloom 2 года назад
Thank you Kevin!
@lewiekab
@lewiekab 5 лет назад
I always wanted to know how fittext worked. Very cool.
@sshuddho
@sshuddho 3 года назад
Tried to use vw as font size, but it was horrible on small screen. This "+ rem" will really help. Thanks Kevin!
@dean6046
@dean6046 5 лет назад
Thank you Ross! Good video
@Brandonstiles
@Brandonstiles 5 лет назад
Great video! I learned a lot!
@franktielemans6624
@franktielemans6624 5 лет назад
Awesome stuff!
@farhanawan9956
@farhanawan9956 5 лет назад
Awesome thank you so much!
@czawiel
@czawiel 5 лет назад
awsome mate! thanks a lot!
@richtraube2241
@richtraube2241 Год назад
Great info, as usual.
@michaeloosthuizen2383
@michaeloosthuizen2383 5 лет назад
I always learn at least one useful thing when watching your videos.
@vjvizar
@vjvizar 5 лет назад
Cool tricks, thanks! :)
@aaronaaronaaron5922
@aaronaaronaaron5922 5 лет назад
o_o dude, you really know about tracks. Thanks ;)
@FER_R
@FER_R 5 лет назад
Just came across this video and subscribed t0 your channel. Really cool content! I will have to play around with it. As a few people here said in the comments, I came for one thing and learned a bunch in the process. Do you know how supported this would be in HTML emails? Most of the CSS I write is tailored to that and I was curious if you had tried it. Thanks.
@holalabellebille
@holalabellebille 5 лет назад
C'est la vie, c'est incroyable ! thanks from france... - Getting out of the container is great. - Object-fit (i didn't know about !) is huge. Merci chef.
@KevinPowell
@KevinPowell 5 лет назад
De rien! And if it's easier for you to write comments in French, go for it. I can read it no problem, I just can't write it to save my life 😂
@stell4you
@stell4you 5 лет назад
"Object-fit" is not supported by edge, so you might wait until MS switches to webkit engine.
@KevinPowell
@KevinPowell 5 лет назад
It's supported by Edge for images, just not video
@TheBorsten
@TheBorsten 5 лет назад
Great Tipps there, Thank you! Especially the font-size trick is really handy. I want to make a suggestion though: To position stuff it’s far less expensive on the rendering (performance) to use transforms rather than margin. You could litterally See the stuttering when resizing the viewport. Margin affects the layout while transforms only touch composite layers.
@johnaweiss
@johnaweiss Год назад
Yes, i noticed the stuttering too. Can you share the transform code to do the same thing?
@TheElkster
@TheElkster 5 лет назад
really interesting!!!! will be having a play! :)
@klaasvaak4110
@klaasvaak4110 4 года назад
The black & white picture on 0:48 is the HQ of ABN AMRO in Amsterdam.
@nazanin_ashrafi
@nazanin_ashrafi 2 года назад
Thank you for the awesome video Kevin 🙏🏻🙏🏻 calc() is so complicated though 😵‍💫😵‍💫
@SalamoYemen
@SalamoYemen 5 лет назад
Top top lesson Thanks so much.
@deathtoby
@deathtoby 3 года назад
Hi Kevin, I was researching on calc() and I realized that calculation can still work with or without the word calc() in the css. And I see from the start of your video, you also omitted it from the width. So I am wondering if you can tell me what is the implications if we omitted it as I couldn't find any website that talks about that. Thanks
@technophile7024
@technophile7024 5 лет назад
Thanks for your hard work and dedication for us! Nice tutorials! May I know which keyboard are you using?
@KevinPowell
@KevinPowell 5 лет назад
It's an old Dell mechanical keyboard. I don't know the model and I'm not on my computer right now, but if I don't answer this now I probably won't see your comment again :\. I did a quick google search, found some that look similar, but I didn't see my exact model
@technophile7024
@technophile7024 5 лет назад
@@KevinPowell Thanks for your swift response! Don't worry! I loved your tutorials!
@xmelsky
@xmelsky 5 лет назад
Very useful function
@gunasekarant6498
@gunasekarant6498 2 года назад
Cool one :-) Thanks @Kevin
@marv92
@marv92 5 лет назад
I came here to kill some time watching some nice tips & tricks and that outside the box thing actually solved one of my biggest pains ever. Thank you so much!
@KevinPowell
@KevinPowell 5 лет назад
So glad to hear that Marvin!
@kolklik
@kolklik 5 лет назад
About the issue with the vw calculations leaving your item to suck up space behind the scrollbar, it's possible to overcome this. If you dont need to worry about IE its fairly simple. The general idea is to calculate the width of the scrollbar using a bit of javascript, then using css custom properties which can be updated by javascript, and used in the margin calculation. Below is a link to a codepen that shows the technique. codepen.io/anon/pen/JVJjzX For those who doesn't want to go look, this is what the margin expression would look like. margin: 0 calc(-50vw + (var(--scrollbar-width) / 2) + 50%); In english this would translate to: "Move it half of the viewports width out. Move it in by whatever the scrollbar-width divided by 2 is. Then move it further in by half of its own width" In order to calculate the scrollbar width you generate a div, with a width that is greater than whatever the scrollbar could possibly be (say 100px) then you get that divs offsetWidth (outer width) and the clientWidth (innerWidth) By subtracting those two numbers, you have the width that the scrollbar occupies. This can then be used to update the css custom property through document.documentElement.style.setProperty. A working example can be seen in the codepen linked above. Having the width of the users scrollbar can be quite handy :-)
@kubakakauko
@kubakakauko 5 лет назад
thanks, that was interesting
@billaddison82
@billaddison82 5 лет назад
Object fit, unreal!
@yassmaboby296
@yassmaboby296 5 лет назад
its really cool useful!
@VovaBlow
@VovaBlow 5 лет назад
*Dear Kevin, your lessons are awesome! Hello from Ukraine!*
@yenumulasrinivasareddy5825
@yenumulasrinivasareddy5825 3 года назад
Thank you kevin,I learnt a new trick today. can we use CSS variables in Calc() like below? ex: font-size: calc( var(--title-fontSize) - 8px); I tried but not working for me. thanks.
@yallayeho1238
@yallayeho1238 5 лет назад
i used it for Containers, which are on the same Level. for example: width: calc(100% / 3) dir Three Containers
@youssefmuhamad3213
@youssefmuhamad3213 5 лет назад
This font-size with calc is perfect for responsiveness, loved it
@himanshuverma3764
@himanshuverma3764 3 года назад
Sir You have to make new layout on topics calc() thanks when i declare width: clac() its is necessary to declare width or not i am confuse sir
@CarlStreet
@CarlStreet 5 лет назад
Nice - Tks!
@twph.5890
@twph.5890 5 лет назад
Thank you :)
@DonAndress
@DonAndress 3 года назад
Is it possible to use calc() to calculate height based on width? I mean, I'd like to set height = width or height = 40% of width. Is it even possible in pure CSS or SASS?
@markjordan7800
@markjordan7800 5 лет назад
using calc with big fonts is super useful ;)
@shohanrahman9392
@shohanrahman9392 3 года назад
4:50 when he uses max-width: 100vw, how come it only fills up the right side and not the entirety of the viewport width? Is it because some other property (like margin-left) overrides it?
@StefanIvanov188
@StefanIvanov188 3 года назад
Hey Im trying to find out how Facebook new design calcs the widh of images containers on their Newsfeed. If you inspect the photo you will see parent div who haves for example if the original width of image is 500x321 then the calc is width: calc(-506.231px + 155.763vh); I can't find out where the "-506.231px" and 155.763vh; are coming from....
@moza260
@moza260 3 года назад
this one is awesome...!!
@0the0ambient0
@0the0ambient0 4 года назад
As a calc believed, thank you!
@borcsaster
@borcsaster 5 лет назад
..love it!
@annagulaev
@annagulaev 4 года назад
Is there a way to cap the font size? It'd be easy if max() was still available. Without that, how do you prevent a huge font on an 8K monitor? :) I use a resize function to re-calculate font sizes, and if not for the maximum font size issue I'd be able to replace the resize function with calc.
@KevinPowell
@KevinPowell 4 года назад
I really wish we had that! And maybe one day, I've heard talk, but for now a media query gets the job done
@tanveerkhan9430
@tanveerkhan9430 5 лет назад
Good tip
@crunckNATIon
@crunckNATIon 5 лет назад
awesome....i had no choice but to subscribe...great content
@KevinPowell
@KevinPowell 5 лет назад
Thanks for the sub, glad you liked it :)
@lucastavares206
@lucastavares206 5 лет назад
I didnt know css had function It seems that i have a lot of ground to cover, since none of the courses i've taken mentioned that
@Alessandro-nq3tm
@Alessandro-nq3tm 5 лет назад
Amazing, best web tutorials on yt!! Please Kevin can you do a pro video about the scss mixins?
@KevinPowell
@KevinPowell 5 лет назад
Got it on my list 😁
@johnaweiss
@johnaweiss Год назад
Can calc use the existing value of an element property?
@AlThePal78
@AlThePal78 Год назад
awesome vid :)
@greenmansession
@greenmansession 5 лет назад
Should definitely do a Sass video ;)
@muhammadrafiuddin8319
@muhammadrafiuddin8319 4 года назад
Thank you sir
@harag9
@harag9 5 лет назад
Having been out of web development for over 10 years, calc is something I wished for back in the day and the vw/vh values. Now having to relearn css again with new updated tricks like this it would be nice to know what browsers support this? I don't want to be using features like this if e.g IE / Edge don't support it.
@KevinPowell
@KevinPowell 5 лет назад
caniuse.com is awesome, gives the browsers, as well as relative usage. Nice thing with this is, even if it doesn't work in IE, it won't break your site, unlike some other properties
@harag9
@harag9 5 лет назад
@@KevinPowell Excellent, thanks for the link to the site - never heard of it before :)
@rushikeshmore2809
@rushikeshmore2809 3 года назад
Hi Kevin, please make video on RFS how it works? And how to use it ?
@JustMeNoOther
@JustMeNoOther 5 лет назад
Thanks!!!!!!
Далее
Floats, Flexbox, Grid? The progression of CSS layouts
27:00
Using CSS Position Absolute: some practical examples
26:18
Avoid these 5 beginner CSS mistakes
21:38
Просмотров 25 тыс.
Use these instead of vh
6:06
Просмотров 440 тыс.
Write less CSS by taking advantage of inheritence
15:52
What would you call this layout?
23:11
Просмотров 31 тыс.
It's time for a change...
4:11
Просмотров 69 тыс.