Thuộc tính CSS height và width được dùng để chỉ định chiều cao và chiều rộng của một phần tử tương ứng. Chúng ta cũng có thể đặt giá trị tối đa và tối thiểu cho các thuộc tính này bằng max-height, max-width, min-height, và min-width.
Cú pháp
Selector {
height: /*value*/
width: /*value*/
}
Kích thước thực tế của phần tử được tính như sau:
| Kích thước hộp | Công thức tính toán |
|---|---|
| Total Width (Tổng chiều rộng) | width + padding-left + padding-right + border-left + border-right + margin-left + margin-right |
| Total Height (Tổng chiều cao) | height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom |
Lưu ý: Với box-sizing: border-box (khuyên dùng), width/height đã bao gồm padding + border.
Ví dụ 1: Width/Height với flexbox
<!DOCTYPE html>
<html>
<head>
<style>
#demo { margin: auto; width: 400px; height: 80px; border: 2px solid black; display: flex; border-radius: 15px; }
#demo div { flex: 1; border: thin dotted; border-radius: 50%; line-height: 60px; text-align: center; }
#orange { box-shadow: inset 0 0 8px orange; }
#green { box-shadow: inset 0 0 8px green; }
#blue { box-shadow: inset 0 0 8px blue; }
#red { box-shadow: inset 0 0 8px red; }
</style>
</head>
<body>
<div id="demo">
<div id="orange">Somebody</div>
<div id="green">that I</div>
<div id="blue">used</div>
<div id="red">to know</div>
</div>
</body>
</html>
Kết quả

Ví dụ 2: Max-width/height với overflow
<!DOCTYPE html>
<html>
<head>
<style>
article { margin: 10% 35%; box-shadow: 0 0 6px 1px black; max-width: 200px; max-height: 150px; overflow: auto; }
</style>
</head>
<body>
<h2>Java 8 Features</h2>
<article> Lambda expression adds functional processing capability to Java. Referencing functions by their names instead of invoking them directly. Interface to have default method implementation. New compiler tools and utilities are added like 'jdeps' to figure out dependencies. New stream API to facilitate pipeline processing. Improved date time API. Emphasis on best practices to handle null values properly. Nashorn, a Java-based engine to execute JavaScript code. </article>
</body>
</html>
Kết quả

Các đơn vị độ dài phổ biến:
| Đơn vị | Loại | Mô tả |
|---|---|---|
px | Absolute | Pixel tuyệt đối |
% | Relative | Phần trăm của containing block |
em | Relative | Font-size của phần tử |
rem | Relative | Font-size của root (<html>) |
vw/vh | Relative | 1% viewport width/height |
vmin/vmax | Relative | Min/Max của vw/vh |
auto | Keyword | Trình duyệt tính toán |
fit-content | Keyword | Vừa nội dung, giới hạn bởi max |
min-content | Keyword | Nhỏ nhất có thể |
max-content | Keyword | Lớn nhất cần thiết |
Min/Max constraints:
min-width/min-height: Phần tử không thể nhỏ hơn giá trị nàymax-width/max-height: Phần tử không thể lớn hơn giá trị này- Thứ tự ưu tiên:
min-width > width > max-width - Rất hữu ích cho responsive design và fluid layouts