首页 > 解决方案 > 使用 css 从 ul li 建表

问题描述

我有这段 html 代码。这是一个 UL/LI 类型的列表,其中包含跨度类。我希望它显示为带有寄宿生的表格,而不是带有项目符号的列表。

<ul class="list">
<li>
<span class="category">category1</span>
<span class="name">Item Title1</span> 
<span class="price">40 EUR</span>
<span class="url"><a href="url1">link to article</a></span>
</li>	
<li>
<span class="category">category2</span>
<span class="name">item title2</span> 
<span class="price">55 EUR</span>
<span class="url"><a href="url2">link to article</a></span>
</li>	
</ul>

我曾尝试编写此 css,但结果并不好。

.list ul {
    width: 450px;           
    position: relative;
    
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.list ul:before, ul:after {
    text-align: center;
    display: block;
    border: 1px solid black;
    border-bottom: 0;
    width: 48%;
}

.list ul:before {
    content: 'col1';
    border-right: 0;    
}

.list ul:after {
    content: 'col2';
    position: absolute;
    top: 0;
    left: 48%;
    margin-left: 1px;    
}

.list li {
    text-align: right;
    width: 48%;
    float: left;
    border: 1px solid black;
    margin-bottom: -1px;
}

.list li:nth-child(even) {
    margin-left: -1px;
}
<ul class="list">
<li>
<span class="category">category1</span>
<span class="name">Item Title1</span> 
<span class="price">40 EUR</span>
<span class="url"><a href="url1">link to article</a></span>
</li>	
<li>
<span class="category">category2</span>
<span class="name">item title2</span> 
<span class="price">55 EUR</span>
<span class="url"><a href="url2">link to article</a></span>
</li>	
</ul>

标签: htmlcsslisthtml-table

解决方案


实现此效果的一种方法是使用CSS Grid

在一开始(当您想重新格式化列表时这很正常),最好先将以下样式应用于父级<ul>/ <ol>

  • margin-left: 0
  • padding-left: 0
  • list-style-type: none

这是对这些类型列表中的任何一种通常显示方式的非常基本的重置。

工作示例:

.list {
  display: grid;
  grid-template-columns: 180px 180px;
  width: 360px;
  margin-left: 0;
  padding-left: 0;
  border: 1px solid rgb(0, 0, 0);
  list-style-type: none;
}

.list li {
  width: 180px;
  border: 1px solid rgb(0, 0, 0);
  box-sizing: border-box;
}

.list li span {
  display: block;
  padding: 6px 9px;
  border: 1px solid rgb(0, 0, 0);
}

.list li span.category {
  font-weight: bold;
  text-align: center;
  text-transform: uppercase;
}
<ul class="list">
<li>
<span class="category">Category 1</span>
<span class="name">Item Title 1</span> 
<span class="price">40 EUR</span>
<span class="url"><a href="url1">Link to Article</a></span>
</li>	
<li>
<span class="category">Category 2</span>
<span class="name">Item Title 2</span> 
<span class="price">55 EUR</span>
<span class="url"><a href="url2">Link to Article</a></span>
</li>	
</ul>


推荐阅读