如何将背景图片扩展到填满整个页面?

3
我正在创建一个固定在左上方的按钮动画,当点击时会创建一个覆盖整个页面的背景。所以我编写了以下 CSS 代码:它只会扩展至其父元素大小,但如何将其制作成能够延伸至整个页面的动画呢?

div {
    height: 200px;
    width: 200px;
    background: radial-gradient(circle at center, blue 50%, transparent 50%);
    background-size: 10% 10%;
    background-position: center;
    background-repeat: no-repeat;
    transition: all .5s;
}

div:hover {
    background-size: 200% 200%;
}
<div></div>

3个回答

1

将高度和宽度分别设置为100vw100vh

我还在body中添加了CSS,以防止元素全屏时出现滚动条。

div {
  height: 200px;
  width: 200px;
  background: radial-gradient(circle at center, blue 50%, transparent 50%);
  background-size: 10% 10%;
  background-position: center;
  background-repeat: no-repeat;
  transition: all .5s;
}

div:hover {
  width: 100vw;
  height: 100vh;
  
  background-size: 200% 200%;
}

body {
  overflow: hidden;
}
<div></div>


1
非常感谢。它可以工作,但似乎随着圆形的扩展而向右移动。我能让这个圆保持固定而扩大吗? - user12653283
我不确定,但我认为这只是扩展宽度/高度的结果 - 我尝试了position: absoluteposition: sticky以及设置topleft,但运气不太好 - 抱歉。 - Shiny

1
您可以考虑以下伪元素:

.box {
  height: 200px;
  width: 200px;
  position: relative;
}

.box:before {
  content: "";
  position: absolute;
  top: -100vh;
  bottom: -100vh;
  left: -100vw;
  right: -100vw;
  background: radial-gradient(circle, blue 50%, transparent 50%) center no-repeat;
  background-size: 20px 20px;
  transition: all .5s;
  pointer-events:none;
}

.box:hover::before {
  background-size: 200% 200%;
}

html {
 overflow:hidden;
}
<div class="box"></div>


当我尝试答案代码时,设置的过渡时间和屏幕填充背景图像的时间之间存在差异。您有办法确保这两个持续时间完全匹配吗? - user12653283
1
@stefano 很难完全匹配它们,因为这个技巧依赖于有一个大的元素溢出屏幕,以确保覆盖屏幕。除非该框始终具有固定的宽度/高度并始终处于相同位置。 - Temani Afif

0

heightwidth 属性分别更改为 100vh100vw

  • vh - 视窗高度
  • vw - 视窗宽度

div {
    height: 200px;
    width: 200px;
    background: radial-gradient(circle at center, blue 50%, transparent 50%);
    background-size: 10% 10%;
    background-position: center;
    background-repeat: no-repeat;
    transition: all .5s;
}

div:hover {
    height: 100vh;
    width: 100vw;
    background-size: 200% 200%;
}
<div></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接