如何解决Hover时Div区域导致页面下方元素移位的问题?
问题修复方案
问题根源
页面内容移位的原因有两个:
- 默认情况下元素的
width/height不包含边框宽度,hover时把右下边框从3px改成5px,导致元素总尺寸变大,挤压下方布局。 - 使用
position: relative偏移元素时,虽然元素占位不变,但边框尺寸变化带来的尺寸增长,还是会推动下方内容移位。
修复步骤
1. 全局启用box-sizing: border-box
给所有元素添加这个属性,让边框宽度包含在元素设置的width/height内,确保边框变化不会改变元素总尺寸。
2. 用transform替代position: relative实现偏移
transform: translate()只会改变元素的视觉位置,不会影响它在布局中的占位空间,不会挤压其他元素。
修改后的代码
CSS部分
/* 全局设置box-sizing,避免边框改变元素尺寸 */ * { box-sizing: border-box; } Html { /*max-width:75%;*/ font-family: "Arial Black"; } div { margin-bottom: 30px; } .film { border: 3px solid black; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; } .film:hover { border-right: 5px solid black; border-bottom: 5px solid black; /* 用transform代替relative定位,不影响布局占位 */ transform: translate(5px, 5px); } .buch { border: 3px solid black; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; float: right; } .buch:hover { border-right: 5px solid black; border-bottom: 5px solid black; transform: translate(5px, 5px); } .games { border: 3px solid black; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; clear: right; } .games:hover { border-right: 5px solid black; border-bottom: 5px solid black; transform: translate(5px, 5px); } .portfolio { border: 3px solid black; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; float: right; } .blog { border: 3px solid black; width: 300px; height: 300px; display: flex; justify-content: center; align-items: center; clear: right; } p { font-size: 45px; line-height: 80%; } .container { display: flex; } .container2 { border: 3px solid black; height: 200px; width: 500px; margin-left: 240px; } a { text-decoration: none; } a:visited { color: black; }
HTML部分(修正了语法错误)
<html lang="de"> <head> <meta charset="utf-8"> <title></title> <style> @import url("CSS_2.css"); </style> </head> <body> <div class="container"> <a href=""> <div class="film"> <p>MOVIES</p> </div> </a> <div class="container2"> <p style="line-height:100%">Hello</p> </div> </div> <a href=""> <div class="buch"> <p>BOOKS</p> </div> </a> <div class="games"> <p>GAMES</p> </div> <div class="portfolio"> <p>PORTFOLIO</p> </div> <div class="blog"> <p>BLOG</p> </div> </body> </html>
内容的提问来源于stack exchange,提问作者user23454794
相关产品推荐
相关产品推荐

