max-content

Baseline Widely available

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

Từ khóa định kích thước max-content biểu diễn kích thước nội tại tối đa của một phần tử. Từ khóa mở rộng phần tử đến kích thước lớn nhất cần thiết để hiển thị nội dung của nó mà không có bất kỳ ngắt dòng mềm nào. Đối với nội dung văn bản, từ khóa này không ngắt dòng nội dung, ngay cả khi nó gây ra tràn nội dung.

Thuộc tính interpolate-size và hàm calc-size() có thể được dùng để kích hoạt hoạt ảnh đến và từ max-content.

Cú pháp

css
/* Used as a length value */
width: max-content;
inline-size: max-content;
height: max-content;
block-size: max-content;

/* Used in grid tracks */
grid-template-columns: 200px 1fr max-content;

Ví dụ

Đặt kích thước hộp với max-content

HTML

html
<div id="container">
  <div class="item">Item</div>
  <div class="item">
    Item with more text in it which will overflow the fixed width box.
  </div>
</div>

CSS

css
#container {
  background-color: #8cffa0;
  padding: 10px;
  width: 200px;
}

.item {
  width: max-content;
  background-color: #8ca0ff;
  padding: 5px;
  margin-bottom: 1em;
}

Kết quả

Đặt kích thước cột grid với max-content

HTML

html
<div id="container">
  <div>Item</div>
  <div>Item with more text in it.</div>
  <div>Flexible item</div>
</div>

CSS

css
#container {
  display: grid;
  grid-template-columns: max-content max-content 1fr;
  grid-gap: 5px;
  box-sizing: border-box;
  height: 200px;
  width: 100%;
  background-color: #8cffa0;
  padding: 10px;
}

#container > div {
  background-color: #8ca0ff;
  padding: 5px;
}

Kết quả

Thông số kỹ thuật

Specification
CSS Box Sizing Module Level 3
# valdef-width-max-content

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

Xem thêm