Thuộc tính cols của đối tượng HTMLTextAreaElement cho phép **lấy hoặc đặt** số cột hiển thị (chiều rộng ước lượng theo số ký tự) của textarea. Giá trị là số nguyên dương. Chiều rộng thực tế phụ thuộc vào font-size, font-family, CSS width (ưu tiên cao hơn).
Cú pháp
// Lấy số cột var c = textarea.cols; // Đặt số cột textarea.cols = 50;
Ví dụ: Thay đổi số cột động
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightseagreen; height: 100vh; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
<body>
<h1>Demo: textarea.cols</h1>
<textarea>Nội dung mẫu trong textarea...</textarea>
<button onclick="setCols()" class="btn">Đặt cols = 50</button>
<script>
function setCols() {
document.querySelector("textarea").cols = 50;
}
</script>
</body>
</html>
Kết quả:
- Ban đầu: Textarea rộng khoảng 20 cột (mặc định).
- Nhấn nút: Chiều rộng mở rộng thành 50 cột.
Lưu ý quan trọng
colslà **gợi ý hiển thị** — không giới hạn độ dài nhập. Dùngmaxlengthđể limit.- CSS
width/max-width**ghi đè**cols. Nên dùng CSS:
textarea { width: 100%; max-width: 600px; box-sizing: border-box; }
cols**bắt buộc** khi dùngwrap="hard"(xem bàitextarea.wrap) — trình duyệt cần biết độ rộng để chèn xuống dòng khi submit.cols="0"hoặc âm: Không hợp lệ, tránh dùng.
Kết hợp rows + cols
Kích thước mặc định chuẩn: <textarea rows="10" cols="50"> — phù hợp cho mô tả sản phẩm, bình luận, ghi chú.
Ví dụ thực tế: Responsive textarea
<style>
.responsive-ta {
width: 100%;
min-height: 120px;
resize: vertical;
box-sizing: border-box;
font-family: inherit;
font-size: 1rem;
line-height: 1.5;
}
</style>
<textarea class="responsive-ta" placeholder="Viết bình luận..."></textarea>
Không cần rows/cols — CSS kiểm soát hoàn toàn, tự co giãn theo container.