Result
CSSだけでどうやってるんだろう、と思ってコード見たらいい発想で感心したので備忘録的に
ホバー方向の検知は疑似要素と間接セレクタを使っています
ちょっと分かりにくいかもなので疑似要素に背景色を追加して可視化します
色が変わっている部分が各方向の疑似要素の角の部分です
疑似要素を回転させ、透明にしてcenterに重ねて方向を検知している、という事みたいです
css
.box { /*親要素*/ margin : 5em auto ; position : relative ; width : 10em ; height : 10em ; line-height : 10em ; overflow : hidden ; } .box__right, .box__left, .box__top, .box__bottom, .box__center { /*各コンテナ*/ position : absolute ; width : inherit ; height : inherit ; text-align : center ; line-height : inherit ; transition : transform . 4 s ease; } .box__right:before, .box__left:before, .box__top:before, .box__bottom:before, .box__center:before { /*各コンテナに疑似要素を追加して角度を変えておく。transform:rotateがキモとなります*/ position : absolute ; content : '' ; width : 70.71% ; height : 70.71% ; transform : rotate ( 45 deg); } .box__right:hover, .box__left:hover, .box__top:hover, .box__bottom:hover, .box__center:hover { /*各要素のホバー設定*/ transform : translateX ( 0 ); z-index : 1 ; } .box__right:hover:before, .box__left:hover:before, .box__top:hover:before, .box__bottom:hover:before, .box__center:hover:before { width : 100% ; height : 100% ; transform : none ; } /*各要素のホバー時の位置遷移設定*/ .box__right { background : #0092ff ; transform : translateX ( 100% ); } .box__right:before { right : 100% ; bottom : 0 ; transform-origin : 100% 100% ; } .box__right:hover ~ .box__center { transform : translateX ( -100% ); } .box__left { background : #75bd3f ; transform : translateX ( -100% ); } .box__left:before { left : 100% ; transform-origin : 0 0 ; } .box__left:hover ~ .box__center { transform : translateX ( 100% ); } .box__top { background : #ea4335 ; transform : translateY ( -100% ); } .box__top:before { top : 100% ; right : 0 ; transform-origin : 100% 0 ; } .box__top:hover ~ .box__center { transform : translateY ( 100% ); } .box__bottom { background : #f5f25f ; transform : translateY ( 100% ); } .box__bottom:before { bottom : 100% ; left : 0 ; transform-origin : 0 100% ; } .box__bottom:hover ~ .box__center { transform : translateY ( -100% ); } .box__center { background : #ff7b0f ; z-index : -1 ; } |
html
< div class = "box" > < div class = "box__right" >Right → Left</ div > < div class = "box__left" >Left → Right</ div > < div class = "box__top" >Top → Bottom</ div > < div class = "box__bottom" >Bottom → Top</ div > < div class = "box__center" > Hover from any side </ div > </ div > |