【问题标题】:CSS background image w/ rotate, repeat and opacity带旋转、重复和不透明度的 CSS 背景图像
【发布时间】:2020-06-01 15:19:47
【问题描述】:

我正在尝试使用图像制作漂亮的背景,但我希望图像重复填充屏幕,不透明度设置为 0.5 并旋转 45 度。我已经尝试了很多方法来实现这一点,但都没有运气。有人有什么想法吗?

在这个 Codepen 中,我将图像旋转且不透明,但无法让背景重复工作。

.background {
  height: 500px;
  width: 500px;
  position: relative;
  display: inline-block;
  padding: 100px;
  border: black 3px solid;
}

.background::before {
  content: "";
  position: absolute;
  overflow: hidden;
  width: 100px;
  height: 100px;
  left: 0;
  top: 0;
  z-index: -1;
  opacity: 0.5;
  background: url(https://cambridgewords.files.wordpress.com/2019/11/funny.jpg);
  background-size: contain;
  transform: rotate(45deg);
  background-repeat: repeat;
  opacity: 0.5;
}
<span class='background'>HElloWorld</span>

【问题讨论】:

    标签: html css background-image


    【解决方案1】:

    你可以这样做:

    .background {
      height: 500px;
      width: 500px;
      position: relative;
      z-index:0;
      display: inline-block;
      overflow:hidden; /* hide the overflow here not on the pseudo element */
      padding: 100px;
      border: black 3px solid;
    }
    
    .background::before {
      content: "";
      position: absolute;
      z-index: -1;
      /* 141% ~ sqrt(2)x100% to make sure to cover all the area after the rotation */
      width: 141%;
      height:141%;
      /**/
      /* to center*/
      left: 50%;
      top: 50%;
      /* */
      background: url(https://cambridgewords.files.wordpress.com/2019/11/funny.jpg);
      background-size: 100px 100px; /* size of the image*/
      transform:translate(-50%,-50%) rotate(45deg); /* center the element then rotate */
      opacity: 0.5;
    }
    <span class='background'>
        HElloWorld
      </span>

    【讨论】:

    • 很好的提示。我想将它用于 背景,我的意思是使用一个小的 PNG 并重新绘制它,但有一些倾向。你能暗示一下吗?在 标签之后是否需要一个包装器 DIV?谢谢
    • 保留相同的代码,但将 .background::before { 替换为 html::before { 而不是绝对使用固定
    • 感谢您的超快速提示回复:-) 然后将在 上设置“背景”类,对吗?谢谢
    • @Robert 不需要它,因为我直接针对 html 元素。我更新了选择器
    • :-( 旋转整个页面内容而背景保持不变
    【解决方案2】:

    尝试增加::before 伪元素的大小,然后像这样减小背景大小:

    .background::before {
        content: "";
        position: absolute;
        overflow: hidden;
        width: 100%; /* made width 100% */
        height: 100%; /* made height 100% */
        left: 0;
        top: 0;
        z-index: -1;
        opacity: 0.5;
        background: url(https://cambridgewords.files.wordpress.com/2019/11/funny.jpg);
        background-size: 100px; /* made background size smaller */
        transform: rotate(45deg);
        background-repeat: repeat;
        opacity: 0.5;
    }
    
    

    这只是使背景伪元素成为元素的全尺寸,然后使背景变小并重复。我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 2011-10-16
      • 2012-05-12
      • 2016-02-26
      • 2017-08-11
      • 2017-07-31
      • 2011-05-29
      • 1970-01-01
      相关资源
      最近更新 更多