要求:寬 50px、高 200px 的直條,交叉形成正十字架,整體水平垂直置中於視窗。
父容器 position: relative(或 body),子元素 position: absolute; left:50%; top:50% + margin-left: -寬度/2; margin-top: -高度/2。
.bar-v { width: 50px; height: 200px; background: #a40000; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -25px; }
.bar-h { width: 200px; height: 50px; background: #a40000; position: absolute; left: 50%; top: 50%; margin: -25px 0 0 -100px; }
HTML:<div class="bar-v"></div><div class="bar-h"></div>
.wrap { width: 200px; height: 200px; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -100px; }
.bar-h { width: 200px; height: 50px; background: #a40000; margin-top: 75px; }
.bar-v { width: 50px; height: 200px; background: #a40000; margin: -125px 0 0 75px; }
容器置中,兩條橫豎條在容器內通過 margin 定位。
.wrap { width: 200px; height: 200px; background: #a40000; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -100px; }
.corner { width: 75px; height: 75px; background: #fff; } /* 白色遮罩蓋住四角 */
.corner-tl, .corner-bl { float: left; }
.corner-tr, .corner-br { float: right; }
.corner-tl, .corner-tr { margin-bottom: 50px; }
原理:200px 正方形背景色為十字架色,四角放 75px 白塊遮出十字形。75*2 + 50 = 200 完美吻合。
要求:圖形為四個角的正方形依次縮小(分形狀),居中於可視區,滿足最多用戶(以 IE6 可視高度 ~590px 為基準)。
中心正方形 200px,每層向外擴展 1/2、1/4、1/8... 幾何級數:
200 + 100×2 + 50×2 + 25×2 + 12.5×2 + 6.25×2 ≈ 590px → 5 層剛好填滿 590px 高度。
.center {
width: 200px; height: 200px;
position: absolute; left: 50%; top: 50%;
margin: -100px 0 0 -100px;
background: #a40000;
}
.corner {
width: 50%; height: 50%;
position: absolute;
background: #a40000;
}
.corner-tl { left: -50%; top: -50%; } /* 左上 */
.corner-tr { right: -50%; top: -50%; } /* 右上 */
.corner-bl { left: -50%; bottom: -50%; } /* 左下 */
.corner-bl { right: -50%; bottom: -50%; } /* 右下 */
<div class="center">
<div class="corner corner-tl">
<div class="corner corner-tl">
<div class="corner corner-tl">
<div class="corner corner-tl">
<div class="corner corner-tl"></div>
</div>
</div>
</div>
</div>
<div class="corner corner-tr">...</div>
<div class="corner corner-bl">...</div>
<div class="corner corner-br">...</div>
</div>
四個角各自遞迴巢狀 5 層,每層尺寸減半、位置向外偏移 50%,形成分形擴展視覺。
body { display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
:root { --size: 200px; --layers: 5; --color: #a40000; }
.center { width: var(--size); height: var(--size); background: var(--color); }
.corner { width: 50%; height: 50%; background: var(--color); }
clip-path 或 mask 替代遮罩 DIV(題目一 5 DIV 方案).cross {
width: 200px; height: 200px; background: #a40000;
clip-path: polygon(
0 37.5%, 37.5% 37.5%, 37.5% 0, 62.5% 0, 62.5% 37.5%, 100% 37.5%,
100% 62.5%, 62.5% 62.5%, 62.5% 100%, 37.5% 100%, 37.5% 62.5%, 0 62.5%
);
}
aria-hidden="true",語意內容提供文字替代。