Home > Web Front-end > CSS Tutorial > How to Transform a Text Input Field into a Password Field Using Only CSS?

How to Transform a Text Input Field into a Password Field Using Only CSS?

DDD
Release: 2024-10-31 12:24:02
Original
690 people have browsed it

How to Transform a Text Input Field into a Password Field Using Only CSS?

How to Make an Input Field Look Like a Password Field with Only CSS

In web development, it is sometimes necessary to display a text input field as a password field with hidden characters, ensuring user privacy. This can be achieved entirely through CSS, even without modifying the HTML or using JavaScript.

CSS Solution:

To transform a text input field into a password-like field, CSS provides an experimental selector called -webkit-text-security (or text-security). This selector controls the visual appearance of input fields and can be used to set the display security for text input.

Implementation:

To use this solution, apply the -webkit-text-security or text-security selector to the desired input field and set the value to disc or another desired character. Here's an example:

<code class="css">input.pw {
  -webkit-text-security: disc;
  text-security: disc;
}</code>
Copy after login

Usage:

To toggle the display between a text and password field, you can add a button to the form and use JavaScript to add or remove the pw class from the input field.

<code class="html"><input type="text" class="pw" value="abcd">

<button onclick="this.previousElementSibling.classList.toggle('pw')">Toggle '•'</button></code>
Copy after login

Browser Compatibility:

The -webkit-text-security selector is supported in modern browsers such as Chrome, Safari, and Opera. For IE8 support, you can use the text-security selector.

Additional Notes:

This solution primarily affects the visual presentation and does not prevent copy/paste functionality by default. However, you can implement additional measures in CSS or JavaScript to restrict copying and pasting from the input field.

The above is the detailed content of How to Transform a Text Input Field into a Password Field Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template