如何在 n 列格式中显示列表?
在本文中,我们将学习如何在 HTML 和 CSS 中使用 columns、column-count 和 grid CSS 属性将列表以“n”列格式显示。
以列的形式显示列表可以是一种节省空间并使信息更具视觉吸引力的有效方法。我们可以使用不同的方法来实现这一点,这些方法分别依赖于 columns、column-count 和 grid 属性。
让我们详细了解每种方法。
方法 1
在这种方法中,我们将使用 column-count CSS 属性来确定我们将内容分成多少列。让我们通过一个示例来了解这一点。
示例
文件名:index.html
<html lang="en">
<head>
<title>How to display a list in n columns format?</title>
<style>
ul {
column-count: 3;
}
</style>
</head>
<body>
<h3>How to display a list in n columns format?</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
</ul>
</body>
</html>
方法 2
在这种方法中,列表项将包装在具有类 list-container 的容器内。通过使用 CSS Flexbox 属性(如 display: flex 和 flex-wrap: wrap),列表项将根据可用空间自动流入多列。
示例
文件名:index.html
<html lang="en">
<head>
<title>How to display a list in n columns format?</title>
<style>
.list-container {
display: flex;
flex-wrap: wrap;
}
.list-item {
flex-basis: 33.33%; /* Adjust this value for the desired number of columns */
}
</style>
</head>
<body>
<h3>How to display a list in n columns format?</h3>
<div class="list-container">
<div class="list-item">Item 1</div>
<div class="list-item">Item 2</div>
<div class="list-item">Item 3</div>
<div class="list-item">Item 4</div>
<div class="list-item">Item 5</div>
<div class="list-item">Item 6</div>
<div class="list-item">Item 7</div>
<div class="list-item">Item 8</div>
<div class="list-item">Item 9</div>
<div class="list-item">Item 10</div>
</div>
</body>
</html>
方法 3
在这种方法中,列表项将包装在具有类 list-container 的容器内。通过利用 CSS Grid 属性(如 display: grid 和 grid-template-columns),项目将根据指定的列数显示在多列中。
示例
文件名:index.html
<html lang="en">
<head>
<title>How to display a list in n columns format?</title>
<style>
.list-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Adjust this value for the desired number of columns */
grid-gap: 10px; /* Adjust the gap between items */
}
</style>
</head>
<body>
<h3>How to display a list in n columns format?</h3>
<div class="list-container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
<div>Item 8</div>
<div>Item 9</div>
<div>Item 10</div>
</div>
</body>
</html>
结论
在本文中,我们学习了如何使用 3 种不同的方法将列表以“n”列格式显示。在第一、第二和第三种方法中,我们使用了 column-count、flexbox 布局和 grid CSS 属性将内容分成所需的列数。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP