The touch-action feature in CSS

css touch action guide
01 December 2024

Introduction

When discussing web page design and development, it is always important to consider user experience and how users interact with the website. One of the key aspects of user interaction with web pages is that they are accessed via touch devices such as smartphones or tablets. The touch-action feature in CSS is one of the tools that allows developers to have more control over the behavior of touch interactions.

Under normal circumstances, browsers automatically manage some touch interactions, such as scrolling or zooming. The touch-action feature allows you to adjust the default behavior of the browser's touch interactions, or even to change it. This feature is particularly relevant in web applications that require touch optimization, as they are essential.

Practical Usage

Using touch-action is necessary to ensure proper functionality across different touch devices. For example, in complex sites that use maps or interactive elements, full control over touch interactions is necessary to ensure all functionalities work correctly.

Sample Code

<style>
.no-touch-action {
touch-action: none;
}

.pan-x {
touch-action: pan-x;
}

.pan-y {
touch-action: pan-y;
}
</style>

<div class="no-touch-action">I have no interaction</div>
<div class="pan-x">I can only scroll in the x direction</div>
<div class="pan-y">I can only scroll in the y direction</div>

Line-by-Line Explanation

<style> - This line starts the CSS style section that defines our CSS features.
.no-touch-action - This class does not allow any default touch behavior. touch-action: none; means no default touch actions are performed.
.pan-x - This class allows scrolling in the x-axis. touch-action: pan-x; enables only horizontal scrolling.
.pan-y - This class allows scrolling in the y-axis. touch-action: pan-y; enables only vertical scrolling.
</style> - This line ends the CSS style section.
<div class="no-touch-action"> - Starts a div block that has no interaction.
I have no interaction - The text inside the div with class .no-touch-action.
</div> - Ends the div block.
The same process applies to the other classes .pan-x and .pan-y explained above.

FAQ

?

Why should we use the touch-action feature?

?

Does the touch-action feature work on all browsers?

?

How can we create a custom touch-action handler?