【问题标题】:CSS centering background imageCSS居中背景图片
【发布时间】:2022-01-25 21:58:54
【问题描述】:

我正在构建一个带有背景图像的项目,但我无法像这样将图像完全居中

我的目标是

我设法做的是

您可以看到图像没有完全垂直居中,如果我调整屏幕大小,铅笔往往会消失。

Here 是有问题的图像。

这里是 CSS 代码:

    .app {
        height: 100%;
        background: url('./background.jpg') no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }

感谢任何可以帮助我的人。

.app {
  height: 100%;
  background: url('https://laaouatni.github.io/w11-clone/images/1dark.jpg') no-repeat center center fixed;
  background-size: cover;
}
<!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>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body class="app">
</body>

</html>

【问题讨论】:

  • 这其实是居中的,但是你想让背景变小对吧?
  • @LaaouatniAnas 完全正确
  • 可以发图片的链接吗?您可以使用像Imgur 这样的照片托管服务,这太棒了,因为您不需要帐户并且是值得信赖的来源
  • 据我所知,您可以使用background-size: contain(如果某些内容会溢出,则会创建一个边框)或手动使用自定义大小,首先写入您想要的背景宽度,然后是高度(这不是最好的,因为图像容易拉伸)background-size: 100vw 100vh;
  • 我试过了,还是不行

标签: javascript html css user-interface sass


【解决方案1】:

尝试使用background-position-y 属性

其实你的背景是居中的,但是图片中的笔没有居中

添加一些代码

所以你可以减少background-position-y 中的数字,比如-10em 在我的电脑上看起来不错

position-y 类似于 translateY 但用于背景(用于垂直移动背景)

或(用更少的代码)

或者为了获得良好的效果,使用 PHOTOSHOP 并裁剪顶部的空间,使图像居中,然后将其放入 HTML

我知道不是最好的,但如果你想要更少的代码¯_(ツ)_/¯ 反应灵敏

.app {
    height: 100%;
    background-image: url('https://i.ibb.co/pWsFM5S/background.jpg');
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    background-attachment: fixed;
    background-position-y: -10em;
}
<!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>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body class="app">
</body>

</html>

【讨论】:

  • 谢谢。我将background-position-y 设置为60%,现在铅笔居中且反应灵敏
  • 感谢我帮助你!使用% 是天才的把戏!因为这真的是响应式
猜你喜欢
  • 2023-01-27
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 2015-03-13
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多