基于现有HTML/CSS,如何实现带交叉线、彩色区块的SWOT分析框?
SWOT分析框的完善实现方案
问题描述
我想要创建标准的SWOT分析框,目前已使用以下HTML和CSS代码搭建了基础结构:
初始CSS代码
.noMargin { margin: 0px; } .bordertp { border-top: 1px solid grey; } .borderbtm { border-bottom: 1px solid grey; } .borderright{ border-right: 1px solid grey; } .borderleft{ border-left: 1px solid grey; }
初始HTML代码
<div class="container"> <div class="row noMargin bordertp borderleft borderright"> <div class="col one borderright"> one </div> <div class="col two"> two </div> </div> <div class="row noMargin borderbtm borderleft borderright"> <div class="col three"> three </div> <div class="col four"> four </div> </div> </div>
但不清楚如何添加中间的交叉分隔线、四个彩色区块以及数字标识,求简便实现方法或现成解决方案。
简便实现方案
不用搞复杂结构,用Flex布局加伪元素就能快速搞定所有需求,直接在现有代码基础上修改就行:
完整CSS代码
/* 重置基础样式,避免默认样式干扰 */ * { box-sizing: border-box; margin: 0; padding: 0; } .container { width: 80%; max-width: 800px; margin: 2rem auto; position: relative; } /* 中间水平分隔线 */ .container::before { content: ''; position: absolute; top: 50%; left: 0; width: 100%; height: 1px; background-color: grey; transform: translateY(-50%); } /* 中间垂直分隔线 */ .container::after { content: ''; position: absolute; left: 50%; top: 0; height: 100%; width: 1px; background-color: grey; transform: translateX(-50%); } .row { display: flex; height: 200px; /* 固定行高保证分隔线居中 */ } .col { flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 1rem; position: relative; border: none; /* 去掉原边框类,避免重复 */ } /* 四个区块的主题配色 */ .one { background-color: #e8f5e9; } /* 优势-绿色系 */ .two { background-color: #fff3e0; } /* 劣势-橙色系 */ .three { background-color: #e3f2fd; } /* 机会-蓝色系 */ .four { background-color: #ffebee; } /* 威胁-红色系 */ /* 左上角数字标识 */ .col::before { content: attr(data-number); position: absolute; top: 0.5rem; left: 0.5rem; font-size: 1.2rem; font-weight: bold; color: rgba(0,0,0,0.7); }
修改后的HTML代码
<div class="container"> <div class="row"> <div class="col one" data-number="1">Strengths<br>内部优势</div> <div class="col two" data-number="2">Weaknesses<br>内部劣势</div> </div> <div class="row"> <div class="col three" data-number="3">Opportunities<br>外部机会</div> <div class="col four" data-number="4">Threats<br>外部威胁</div> </div> </div>
方案说明
- 交叉分隔线:靠容器的两个伪元素生成水平、垂直分隔线,用绝对定位+transform实现居中,不用额外加DOM元素。
- 彩色区块:直接给每个区块的类设置对应背景色,贴合SWOT各模块的常用视觉区分。
- 数字标识:用
data-number属性存数字,配合伪元素渲染到左上角,不用额外加标签,改数字直接改属性就行。 - 简化了原有的边框类,靠伪元素分隔线替代,结构更清爽。
内容的提问来源于stack exchange,提问作者kanishka
相关产品推荐
相关产品推荐

