CSS to modify placeholder content

Change placeholder content with CSS

Change placeholder content with CSS

In web development, the placeholder attribute of a form is used to describe the expected content in an input box. Normally, browsers automatically display gray text in the input field based on this attribute to help users fill out the form correctly. However, sometimes we want to customize the style of the placeholder, such as changing the font color or size or modifying the text content. This article will detail how to modify the style of placeholder content using CSS.

How it Works

Actually, placeholders are pseudo-elements generated by the browser by default, so their styles cannot be modified directly using CSS selectors. However, we can use some pseudo-element selectors and attribute selectors to modify the style of the placeholder content.


Method 1: Use the ::-webkit-input-placeholder and ::-moz-placeholder pseudo-classes

For different browsers, we can use ::-webkit-input-placeholder and ::-moz-placeholder to modify the style of the placeholder content. Here’s an example:

/* Webkit browsers */ 
::-webkit-input-placeholder {
color: red;
font-size: 14px;
} 

/* Mozilla Firefox */ 
::-moz-placeholder {
color: red;
font-size: 14px;
} 

This changes the color of the placeholder content to red and the font size to 14px.

Method 2: Use the :-ms-input-placeholder selector

For Internet Explorer, we can use the :-ms-input-placeholder selector to modify the style of the placeholder content. An example is as follows:

/* Internet Explorer */
:-ms-input-placeholder {
color: red;
font-size: 14px;
}

Similarly, this method changes the placeholder content color to red and the font size to 14px in Internet Explorer.

Case Demonstration

Below, we use a simple HTML file and CSS style sheet to demonstrate how to modify the style of the placeholder content:

<!DOCTYPE html> 
<html Tutorial">html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Modify the placeholder content style</title> 
<link rel="stylesheet" href="style.css"> 
</head> 
<body> 
<input type="text" placeholder="Please enter your username"> 
</body> 
</html> 
/* style.css */
::placeholder {
color: red;
font-size: 14px;
}

In the above example, we use the ::placeholder selector to modify the style of the placeholder content, changing its color to red and its font size to 14px. Save the above code as index.html and style.css. Open the index.html file in a browser and you’ll see that the style of the placeholder content in the input box has changed.

Conclusion

Through the above method, we can easily use CSS to modify the style of the placeholder content, making the form more beautiful and in line with design requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *