- Instant help with your CSS coding problems

How to use calc() in TailwindCSS

Question:
How to use calc() in TailwindCSS?
Answer:
/* Set top margin depending on screen height */
<div class="mt-[calc(100vh_/_5)]">
Description:

calc() is a commonly used CSS function. It's useful if you want to dynamically change the position of individual components. 

For TailwindCSS it is very important that space characters are not allowed in the expression. So, unlike normal CSS, you either have to type everything without space or use underscore characters instead of space characters.

So calc(100vh / 5) becomes calc(100vh/5) or calc(100vh_/_5)

For example, if you want a modal dialogue window to be displayed closer to the top of the screen than in the middle. Since we don't know the client screen resolution in advance, the value of the top margin has to be calculated dynamically.

<div class="fixed bg-slate-400 bg-opacity-70 top-0 bottom-0 left-0 right-0 flex justify-center">
	<div class="p-5 bg-white rounded w-96 h-24 shadow mt-[calc(100vh_/_5)]">Dialog</div>
</div>

The result is:

 

Share "How to use calc() in TailwindCSS?"
Interesting things
OpanAi's ChatGPT