CSS实现DIV居中异常求助:优化样式并设宽度为75%
解决DIV无法正确居中的CSS修正方案
问题描述
DIV无法正确居中,经排查是CSS配置导致。需要修正CSS代码,移除不必要声明,实现DIV水平居中且宽度设置为75%。
当前CSS代码
.css_main_popup { transition: opacity 10ms; visibility: hidden; position: absolute; top: 10px; right: 10px; font-size: 30px; font-weight: bold; text-decoration: none; color: #333; margin: auto; margin-left: auto; margin-right: auto; padding: 10px; background: #fff; border-radius: 5px; width: 95%; height: 90%; overflow: auto; align-self: center; }
当前HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SMT Explorer</title> <link rel="stylesheet" href="explorer.css"> <link rel="stylesheet" href="main.css"> </head> <body> <div id="main_div" style="position: relative; "></div> <div id="popup_factory" class="css_main_popup"> <a class="css_close_popup" href="#" style='text-align:right' onclick="CloseFPopup()">×</a> </div> <div id="popup_stations" class="css_main_popup"> <a class="css_close_popup" href="#" style='text-align:right' onclick="CloseSPopup()">×</a> </div> <script type="text/javascript" src="explorer.js"></script> </body> </html>
修正后的CSS代码
.css_main_popup { transition: opacity 10ms; visibility: hidden; position: absolute; top: 10px; font-size: 30px; font-weight: bold; text-decoration: none; color: #333; margin: 0 auto; padding: 10px; background: #fff; border-radius: 5px; width: 75%; height: 90%; overflow: auto; left: 0; right: 0; }
关键修改说明
- 移除
right: 10px:该声明强制元素固定在右侧,直接阻断居中效果 - 简化margin为
margin: 0 auto:替代重复的margin-left/right: auto,实现水平居中 - 添加
left: 0和right: 0:绝对定位元素需同时设置左右为0,才能让margin: auto生效实现水平居中 - 将
width: 95%改为width: 75%:满足宽度要求 - 移除
align-self: center:该属性属于flex布局范畴,对绝对定位元素无效
内容的提问来源于stack exchange,提问作者Mi Po
相关产品推荐
相关产品推荐

