Thuộc tính wordWrap (CSS overflow-wrap) cho phép ngắt từ dài xuống dòng tiếp theo khi cần thiết.
Cú pháp
// Lấy giá trị object.style.wordWrap // Thiết lập giá trị object.style.wordWrap = "value"
Giá trị
| Giá trị | Mô tả |
|---|---|
| initial | Trả về giá trị mặc định. |
| inherit | Kế thừa từ phần tử cha. |
| normal | Chỉ ngắt từ khi cần thiết (mặc định). |
| break-word | Cho phép ngắt từ dài không thể ngắt được. |
Ví dụ: Bật wordWrap khi click nút
<!DOCTYPE html>
<html>
<head>
<style>
p { border: 2px solid #fff; width: 100px; }
.btn { background: #db133a; color: #fff; border: none; padding: 0.5rem 1rem; cursor: pointer; }
</style>
</head>
<body>
<h1>DOM Style wordWrap Property</h1>
<p>This is a paragraph element. This is a veryveryveryverylongword. This is another veryveryverylongword.</p>
<button onclick="add()" class="btn">Set wordWrap</button>
<script>
function add() {
document.querySelector('p').style.wordWrap = "break-word";
}
</script>
</body>
</html>
Ban đầu từ dài tràn ra ngoài, sau khi click nút, từ được ngắt xuống dòng.