You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Django生成的textarea表单元素应用CSS的技术问询

Fixing CSS Styling for Django-Generated Textarea

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:00:18