container

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since February 2023.

Thuộc tính CSS containerthuộc tính viết tắt dùng để thiết lập phần tử thành một container truy vấn và chỉ định tên cũng như kiểu của ngữ cảnh containment được sử dụng trong container query.

Các thuộc tính thành phần

Thuộc tính này là dạng viết tắt của các thuộc tính CSS sau:

Cú pháp

css
/* <container-name> */
container: my-layout;

/* <container-name> / <container-type> */
container: my-layout / size;

/* Global Values */
container: inherit;
container: initial;
container: revert;
container: revert-layer;
container: unset;

Giá trị

<container-name>

Tên phân biệt chữ hoa/thường cho ngữ cảnh containment. Chi tiết về cú pháp được đề cập trong trang thuộc tính container-name.

<container-type>

Kiểu của ngữ cảnh containment. Chi tiết về cú pháp được đề cập trong trang thuộc tính container-type.

Định nghĩa hình thức

Initial valueas each of the properties of the shorthand:
Applies toall elements
Inheritedno
Percentagesas each of the properties of the shorthand:
Computed valueas each of the properties of the shorthand:
Animation typeas each of the properties of the shorthand:

Cú pháp hình thức

container = 
<'container-name'> [ / <'container-type'> ]?

<container-name> =
none |
<custom-ident>+

<container-type> =
normal |
[ [ size | inline-size ] || scroll-state ]

Ví dụ

Thiết lập containment theo kích thước inline

Với ví dụ HTML sau đây là thành phần card có hình ảnh, tiêu đề và một số văn bản:

html
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>

Cách tường minh để tạo ngữ cảnh container là khai báo container-type với tên container-name tùy chọn:

css
.post {
  container-type: inline-size;
  container-name: sidebar;
}

Thuộc tính viết tắt container giúp đơn giản hóa việc khai báo này trong một dòng duy nhất:

css
.post {
  container: sidebar / inline-size;
}

Sau đó bạn có thể nhắm đến container đó theo tên bằng quy tắc at-rule @container:

css
@container sidebar (width >= 400px) {
  /* <stylesheet> */
}

Thông số kỹ thuật

Specification
CSS Conditional Rules Module Level 5
# container-shorthand

Khả năng tương thích trình duyệt

Xem thêm