如何用CSS实现适配全屏幕的背景分区:左至中蓝,上中至右下白
Hey there! Looking to nail that responsive split background where the left-to-middle area stays blue and the upper-middle to bottom-right section is white? Let's tweak your existing code to make it work flawlessly across every screen size.
The Problem with Your Current Code
Your approach uses fixed percentage offsets (top: -70%, right: -50%) which can misbehave on extreme screen ratios—think super wide desktop monitors or tall mobile devices. The rotated white element might not cover the intended area consistently.
Refined Rotated Element Approach
This version ensures the white slanted section always fits perfectly, no matter the screen size:
/* Full-screen blue base background */ .wrapper { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: #297fca; z-index: 1; } /* Responsive white slanted section */ .right { position: fixed; top: 0; right: 0; /* Make it larger than the viewport to ensure coverage on any screen */ width: 140vw; height: 140vh; background-color: #fff; /* Anchor rotation to the top-right corner for consistent slant */ transform-origin: top right; /* Rotate to create the upper-middle to bottom-right slant */ transform: rotate(-45deg); z-index: 2; }
Why This Works:
- Uses
vw/vhunits to scale with the viewport. - Oversizing the white element (
140vw/140vh) guarantees it covers the required area even on odd screen ratios. transform-origin: top rightkeeps the slanted edge aligned correctly as the screen resizes.
Alternative: Clean Shape with clip-path
If you prefer a more precise, non-oversized element, use clip-path to define the exact white area directly:
.wrapper { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: #297fca; } .right { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: #fff; /* Clip to a shape that starts at top-middle and extends to bottom-right */ clip-path: polygon(50% 0, 100% 0, 100% 100%, 0 100%); z-index: 2; }
Note on clip-path:
The polygon() values define the white area's boundaries:
50% 0: Top-middle of the screen100% 0: Top-right corner100% 100%: Bottom-right corner0 100%: Bottom-left corner
This creates a clean diagonal split from top-middle to bottom-left, keeping the left-to-middle area blue and the upper-middle to bottom-right area white.
内容的提问来源于stack exchange,提问作者Johannes




