html - 使用 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>
解决方案
实现此效果的一种方法是使用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>
推荐阅读
- react-native - React-native 中是否有隐式参数名称
- python - 如何处理类层次结构中的python装饰器?
- swift - Access last element in XCUIElement
- javascript - Vue JS V-For component reactivity
- javascript - 在弹出窗口中定位元素
- rest - 为 POST 和 DELETE 方法返回字符串文字而不是值对象是不好的做法吗?
- javascript - 如何在数组中搜索产品“项目类型”并以“项目类型”的名称发送到工作表?
- while-loop - 嵌套while循环的代码时间复杂度
- mpdf - Mpdf 库不会在浏览器中输出 PDF 而总是下载
- javascript - 如何在 Angular 组件之间传递布尔值以切换样式的显示