为Django生成的textarea表单元素应用CSS的技术问询
Let's break down why your Django-rendered textarea isn't picking up the CSS, and fix it step by step:
1. The Root Cause
Your current CSS uses this selector:
textarea[type=textarea] { ... }
But here's the problem: the <textarea> HTML element doesn't support a type attribute—you manually added type="Textarea" to your hand-written textarea, which is why that one works. Django's forms.Textarea widget generates a plain <textarea> tag without this custom type attribute, so your CSS selector completely ignores it.
Also, your font-size: 33 is missing a unit (like px), which browsers will interpret incorrectly.
2. Solution 1: Style All Textareas (Quick Fix)
Update your CSS to target all <textarea> elements directly, and add the missing px unit:
textarea { width: 20%; padding: 21px 20px; margin: 14px 0; box-sizing: border-box; font-size: 33px; /* Added required px unit */ border: 2px solid red; border-radius: 4px; font-family: Arial; }
This will apply the style to both your hand-written textarea and the one generated by Django.
3. Solution 2: Target Only Django's Textarea (Precise Control)
If you want to style just the Django-generated textarea (and leave other textareas untouched), add a custom class to the widget in forms.py:
from django import forms class CommentForm(forms.Form): name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'placeholder':'Your Name Please'})) comment = forms.CharField(widget=forms.Textarea(attrs={ 'placeholder':'Your comment to the world', 'class': 'custom-comment-textarea' # Add custom class here }))
Then update your CSS to use this class selector:
.custom-comment-textarea { width: 20%; padding: 21px 20px; margin: 14px 0; box-sizing: border-box; font-size: 33px; border: 2px solid red; border-radius: 4px; font-family: Arial; }
Bonus tip: You can remove the unnecessary type="Textarea" from your hand-written textarea—HTML doesn't require that attribute for textarea elements.
内容的提问来源于stack exchange,提问作者Compoot

