不同页面textarea样式覆盖rows/cols属性问题求助
解决textarea CSS样式覆盖rows/cols属性的问题
看起来你遇到的核心问题有两个:一是通用的textarea CSS选择器会匹配所有文本域元素,导致第二个textarea被统一样式覆盖;二是CSS的width/height属性优先级高于HTML原生的rows/cols,所以即使你设置了后者也会被CSS样式覆盖。
下面给你两种可行的解决方案:
方案1:使用类选择器区分不同textarea
给每个textarea添加不同的类名,然后在CSS中针对类编写样式,既能精准控制每个文本域的外观,也能灵活选择是否保留rows/cols的作用(如果需要让原生属性生效,记得去掉对应CSS中的width/height,或者用min-height/max-width这类属性兼容)。
修改后的CSS代码:
/* 所有textarea的基础通用样式 */ textarea { padding: 12px 20px; box-sizing: border-box; border: 5px solid #D8FF01; border-radius: 4px; background-color: #000; color: white; font-weight: bolder; resize: both; } /* 第一个textarea的专属样式 */ .textarea-primary { width: 40%; height: 75px; } /* 第二个textarea的专属样式(可自定义或保留rows/cols) */ .textarea-secondary { /* 若想让rows/cols生效,注释掉height改用auto */ /* height: auto; */ width: 50%; height: 120px; }
修改后的HTML代码:
<form> <textarea class="textarea-primary" name="comment" placeholder="Enter..."></textarea> </form> <!-- 第二个页面的表单 --> <form> <textarea class="textarea-secondary" name="feedback" placeholder="Enter your feedback..." rows="8" cols="60"></textarea> </form>
方案2:使用ID选择器(适合单个特殊textarea)
如果你的第二个textarea是唯一的,也可以用ID选择器设置样式,它的优先级会比通用的textarea选择器更高:
CSS代码片段:
/* 通用textarea样式保持不变 */ textarea { width: 40%; height: 75px; padding: 12px 20px; box-sizing: border-box; border: 5px solid #D8FF01; border-radius: 4px; background-color: #000; color: white; font-weight: bolder; resize: both; } /* 针对ID为textarea1的文本域覆盖样式 */ #textarea1 { width: 60%; height: auto; /* 让rows属性生效 */ }
HTML代码片段:
<!-- 第二个页面的表单 --> <form> <textarea id="textarea1" name="comment" placeholder="Enter..." rows="10" cols="50"></textarea> </form>
关键提醒:你之前用的textarea1选择器是无效的——CSS中ID选择器需要加#前缀,类选择器需要加.前缀,直接写textarea1会被当成不存在的标签选择器,所以样式不会生效。
内容的提问来源于stack exchange,提问作者Brad Anderson
相关产品推荐
相关产品推荐

