html - CSS 不居中
问题描述
我可能会在这里被烤焦,但我已经将我的 Photoshop 图层导出到 CSS,UI 看起来是正确的,但都在左侧居中。我已经尝试了我所知道的一切,但中间似乎没有任何东西。因为我希望 UI 能够响应,所以这对我来说有点挑战。我已将设置恢复为默认值。
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="background"></div>
<div class="backgroundFiller"></div>
<div class="gameBackground"></div>
<div class="buttonRight"></div>
<div class="buttonMiddle"></div>
<div class="buttonLeft"></div>
<div class="screen"></div>
<div class="rep"></div>
</body>
</html>
CSS:
.rep {
background-image: url("rep.png");
position: absolute;
left: 98px;
top: 403px;
width: 238px;
height: 24px;
z-index: 8;
}
.buttonLeft {
background-image: url("buttonLeft.png");
position: absolute;
left: 98px;
top: 496px;
width: 213px;
height: 64px;
z-index: 5;
}
.buttonMiddle {
background-image: url("buttonMiddle.png");
position: absolute;
left: 405px;
top: 496px;
width: 213px;
height: 64px;
z-index: 6;
}
.buttonRight {
background-image: url("buttonRight.png");
position: absolute;
left: 712px;
top: 496px;
width: 213px;
height: 64px;
z-index: 7;
}
.screen {
background-image: url("screen.png");
position: absolute;
left: 98px;
top: 119px;
width: 827px;
height: 264px;
z-index: 4;
}
.gameBackground {
background-image: url("gameBackground.png");
position: absolute;
left: 68px;
top: 96px;
width: 886px;
height: 573px;
z-index: 3;
}
.backgroundFiller {
background-image: url("backgroundFiller.png");
position: absolute;
left: 39px;
top: 51px;
width: 946px;
height: 666px;
z-index: 2;
}
.background {
background-image: url("Background.png");
position: absolute;
left: 0px;
top: 0px;
width: 1024px;
height: 768px;
z-index: 1;
}
解决方案
您正在使用绝对位置,然后使用 left 属性设置左侧的距离。例如,.rep 距左侧仅 98px,距顶部仅 403px。
我会将位置更改为相对位置,然后用于margin: 0 auto;
水平居中元素。如果要保持绝对位置:
- 将左侧属性设置为 50%。
- 添加一个等于元素宽度一半的负左边距。
如果您还想垂直居中:
- 添加顶部:50%。
- 然后添加一个等于其高度一半的负上边距。
对于响应性,我建议使用响应式单位,如 %、vh(高度)、wh(宽度)、rem、em,而不是像 px 这样的固定单位。
希望这对您有所帮助。
推荐阅读
- html - Google Maps info Bubble with Font Awesome Icons and bootstrap?
- java - 在二维数组的 IF 语句中使用 AND OR 对行的值求和
- mysql - Pomelo MySqlException:无法连接到任何指定的 MySQL 主机
- java - /storage/emulated/0/Notes/(没有这样的文件或目录)?
- mysql - 左连接 MYSQL 查询中的重复项
- python - 在 Python 中处理 json api 响应的问题
- jquery - CakePHP 2 无法识别通过 ajax 上传的文件
- jquery - 图像旋转后的选择区域
- java - Eclipse & Intellij DE - 无法连接到 mysql 数据库
- python - 不支持编码时如何从 DBF 文件中删除字段?