web-dev-qa-db-fra.com

fond: fixe pas de répétition ne fonctionne pas sur mobile

Je construis une page Web sur laquelle je veux que l’image d’arrière-plan soit redimensionnée pour s’adapter à l’ensemble de l’écran, pour conserver les proportions et pour être corrigée (ainsi, si vous faites défiler l'écran vers le bas, l'image d'arrière-plan reste au même endroit).

J'ai réalisé cela dans les navigateurs de bureau avec le CSS ci-dessous, mais cela ne fonctionne pas sur un iPhone ou un iPad. Sur ces appareils, l’arrière-plan est trop grand (il reste au-dessous du pli) et si vous faites défiler le texte suffisamment loin, l’image se répète. Quelqu'un a un problème? Merci!

HTML {
  background: url(photos/2452.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
26
user2874270

J'ai trouvé une excellente solution pour les arrière-plans fixes sur des appareils mobiles ne nécessitant aucun JavaScript.

body:before {
  content: "";
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -10;
  background: url(photos/2452.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Soyez conscient de la valeur négative de z-index de -10. html élément racine par défaut z-index est 0. Cette valeur doit être la plus petite z-index pour l’avoir en arrière-plan.

85
Vincent

J'ai eu une très simple solution pour cela, après avoir lutté avec toutes les méthodes pour résoudre ce problème.

j'ai eu le problème sur mes appareils mobiles IOS.

css (bureau)

#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}

Ensuite, je l’écrase avec une requête de média supprimant "corrigée" comme pièce jointe en arrière-plan.

css (mobile)

@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}

initial - Définit cette propriété sur sa valeur par défaut. Je pense que, parce que IOS n'accepte pas 'fixe', il revient à une valeur par défaut qu'il accepte, faites défiler.

Cela a fonctionné pour moi sur chaque appareil. J'espère que cela aide aussi quelqu'un d'autre.

4
Ylama

J'ai trouvé peut-être la meilleure solution pour parallax effect qui fonctionne sur tous les périphériques .

L'essentiel est de définir toutes les sections avec z-index supérieur à la section de parallaxe. 

Et élément d'image parallaxe à définir fixe avec une largeur et une hauteur maximales

body, html { margin: 0px; }
section {
  position: relative; /* Important */
  z-index: 1; /* Important */
  width: 100%;
  height: 100px;
}

section.blue { background-color: blue; }
section.red { background-color: red; }

section.parallax {
  z-index: 0; /* Important */
}

section.parallax .image {
  position: fixed; /* Important */
  top: 0; /* Important */
  left: 0; /* Important */
  width: 100%; /* Important */
  height: 100%; /* Important */
  background-image: url(https://www.w3schools.com/css/img_fjords.jpg);
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<section class="blue"></section>
<section class="parallax">
  <div class="image"></div>
</section>
<section class="red"></section>

1
Nebojsa Sapic

Nous avons trouvé une solution parfaite au problème 100% de travail sur mobile et sur ordinateur

https://codepen.io/mrinaljain/pen/YObgEP

.jpx-is-wrapper {
    display: block;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
    z-index: 314749261;
    width: 100vw;
    height: 300px
}

.jpx-is-wrapper>.jpx-is-container {
    background-color: transparent;
    border: 0;
    box-sizing: content-box;
    clip: rect(auto auto auto auto);
    color: black;
    left: 0;
    margin: 0 auto;
    overflow: visible;
    position: absolute;
    text-align: left;
    top: 0;
    visibility: visible;
    width: 100%;
    z-index: auto;
    height: 300px
}

.jpx-is-wrapper>.jpx-is-container>.jpx-is-content {
    left: 0;
    overflow: hidden;
    right: 0;
    top: 0;
    visibility: visible;
    width: 100%;
    position: relative;
    height: 300px;
    display: block
}

.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad {
    -webkit-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;
    -moz-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;
    box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;
    bottom: 26px;
    left: 0;
    margin: 0 auto;
    right: 0;
    text-align: center;
    height: 588px;
    top: 49px;
    bottom: auto;
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0)
}

.jpx-position-fixed {
    position: fixed
}

.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad>.jpx-is-ad-frame {
    width: 100%;
    height: 100%
}

.black-fader {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 100%;
    opacity: 0.75
}

.video-containers {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: 0
}

.video-containers video,.video-containers img {
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>

<div class="jpx-is-wrapper">
                       <div class="jpx-is-container">
                          <div class="jpx-is-content">
                             <div class="jpx-is-ad jpx-position-fixed">
                                   <div scrolling="no" width="100%" height="100%" class="jcl-wrapper" style="border: 0px; display: block; width: 100%; height: 100%;">
                                       <div class="video-containers" id="video-container">
                                          <img src="https://via.placeholder.com/350x150" alt="" class="">
                                       </div>
                                  </div>
                             </div>
                          </div>
                       </div>
                    </div>

<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>

1
Mrinal Jain

Grâce aux efforts de Vincent et au travail de Joey Hayes, ce codepen fonctionne sur un mobile Android prenant en charge plusieurs arrière-plans fixes. 

HTML:

<html>

<body>
  <nav>Nav to nowhere</nav>
  <article>

    <section class="bg-img bg-img1">
      <div class="content">
        <h1>Fixed backgrounds on a mobile browser</h1>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section>
      <div class="content">
        <p>Quid securi etiam tamquam eu fugiat nulla pariatur. Cum ceteris in veneratione tui montes, nascetur mus. Quisque placerat facilisis egestas cillum dolore. Ambitioni dedisse scripsisse iudicaretur. Quisque ut dolor gravida, placerat libero vel,
          euismod.
        </p>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section class="footer">
      <div class="content">
        <h3>The end is nigh.</h3>
      </div>
    </section>

  </article>
  </body>

CSS:

* {
  box-sizing: border-box;
}

body {
  font-family: "source sans pro";
  font-weight: 400;
  color: #fdfdfd;
}
body > section >.footer {
  overflow: hidden;
}

nav {
  position: fixed;
  top: 0;
  left: 0;
  height: 70px;
  width: 100%;
  background-color: silver;
  z-index: 999;
  text-align: center;
  font-size: 2em;
  opacity: 0.8;
}

article {
  position: relative;
  font-size: 1em;
}

section {
  height: 100vh;
  padding-top: 5em;
}

.bg-img::before {
  position: fixed;
  content: ' ';
  display: block;
  width: 100vw;
  min-height: 100vh;  
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-position: center;
  background-size: cover;
  z-index: -10; 
}

.bg-img1:before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326836/3balls_1280.jpg');
}
.bg-img2::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326840/icebubble-1280.jpg');
}
.bg-img3::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326844/soap-bubbles_1280.jpg');
}

h1, h2, h3 {
  font-family: lato;
  font-weight: 300;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.content {
  max-width: 50rem;
  margin: 0 auto;
}
.solid {
  min-height: 100vh;
  width: 100%;
  margin: auto;
  border: 1px solid white;
  background: rgba(255, 255, 255, 0.6);
}

.footer {
  background: rgba(2, 2, 2, 0.5);
}

JS/JQUERY

window.onload = function() {

  // Alternate Background Page with scrolling content (Bg Pages are odd#s)
  var $bgImg = $('.bg-img');
  var $nav = $('nav');
  var winh = window.innerHeight;
  var scrollPos = 0;
  var page = 1;
  var page1Bottom = winh;
  var page3Top = winh;
  var page3Bottom = winh * 3;
  var page5Top = winh * 3;
  var page5Bottom = winh * 5;

  $(window).on('scroll', function() {

    scrollPos = Number($(window).scrollTop().toFixed(2));
    page = Math.floor(Number(scrollPos / winh) +1);
    if (scrollPos >= 0 && scrollPos < page1Bottom ) {    
      if (! $bgImg.hasClass('bg-img1')) {

        removeBg( $bgImg, 2, 3, 1 ); // element, low, high, current
        $bgImg.addClass('bg-img1');
      }
    } else if (scrollPos >= page3Top && scrollPos <= page3Bottom) {
      if (! $bgImg.hasClass('bg-img2')) {

        removeBg( $bgImg, 1, 3, 2 ); // element, low, high, current
        $bgImg.addClass('bg-img2');
      }
    } else if (scrollPos >= page5Top && scrollPos <= page5Bottom) {
      if (! $bgImg.hasClass('bg-img3')) {

        removeBg( $bgImg, 1, 2, 3 ); // element, low, high, current
        $bgImg.addClass('bg-img3');
      }
    }
    $nav.html("Page# " + page + " window position: " + scrollPos);

  });
}

// This function was created to fix a problem where the mouse moves off the
// screen, this results in improper removal of background image class. Fix
// by removing any background class not applicable to current page.
function removeBg( el, low, high, current ) {
  if (low > high || low <= 0 || high <= 0) {
    console.log ("bad low/high parameters in removeBg");
  }
  for (var i=low; i<=high; i++) {
    if ( i != current ) { // avoid removing class we are trying to add
      if (el.hasClass('bg-img' +i )) {
        el.removeClass('bg-img' +i );
      }
    }
  } 
} // removeBg()
1
Eggs

background-attachment:fixed dans IOS Safari est un bogue connu depuis aussi longtemps que je me souvienne.

Voici quelques autres options pour vous:

https://stackoverflow.com/a/23420490/1004312

Étant donné que la position fixe en général n’est pas très stable au toucher (certaines plus que d’autres, Chrome fonctionne très bien), elle fonctionne toujours dans Safari IOS 8 dans des situations qui fonctionnaient auparavant dans IOS 7 Par conséquent, j’utilise généralement JS pour détecter les appareils tactiles, y compris Windows Mobile.

/* ============== SUPPORTS TOUCH OR NOT ========= */
/*! Detects touch support and adds appropriate classes to html and returns a JS object
  Copyright (c) 2013 Izilla Partners Pty Ltd  | http://www.izilla.com.au 
  Licensed under the MIT license  |  https://coderwall.com/p/egbgdw 
*/
var supports = (function() {
    var d = document.documentElement,
        c = "ontouchstart" in window || navigator.msMaxTouchPoints;
    if (c) {
        d.className += " touch";
        return {
            touch: true
        }
    } else {
        d.className += " no-touch";
        return {
            touch: false
        }
    }
})();

L'exemple CSS suppose que le mobile est le premier:

.myBackgroundPrecious {
   background: url(1.jpg) no-repeat center center;
   background-size: cover;
}

.no-touch .myBackgroundPrecious {
   background-attachment:fixed;
}
1
Christina

Je suis occupé à utiliser différents messages et méthodes pendant deux jours pour essayer de le comprendre. J'exhorte quiconque à COMMENCER en regardant le message écrit par Eggs et à perdre son temps avec le codepen que lui et d'autres ont construit.

C’est la seule solution que j’ai trouvée qui fonctionne correctement pour moi. Je recommande sa réponse comme solution/un bon point de départ au minimum pour ceux d’entre nous qui résolvons encore ce problème dans nos propres applications Web.

Je n'ai pas encore assez de réputation pour commenter son message, sinon je le ferais. Je ne peux même pas voter pour le moment, sinon je le ferais aussi.

C'est le code que j'ai utilisé:

html::before {
    content: ' ';
    display: block;
    background-image: url('path-to-your-image');
    background-position: bottom left; 
    /*For my instance this is how I have built my bg image. Indexes off the 
bottom left for consistency*/
    background-size: cover;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    position: fixed;
    z-index: -10; 
    /*I haven't tested my full app functionality after changing the z-index, but everything appears to work flawlessly right now.*/
}

J'ai tout essayé avec son code d'origine. Quand j'avais 

background-position: center; 

chrome (sur la dernière mise à jour Android du 1/8/18) traînait avec la mise à jour de la position de l'image. Ainsi, lors du défilement du site Web, il y aurait un patch de couleur à l'emplacement de la barre de barre de navigation/URL du navigateur. Ensuite, il disparaîtrait une fois que le navigateur aurait recalculé le centre de l'image (c'est ce que je suppose qui se passait).

Je vous recommande donc de créer une image autour de votre pied de page ou de votre en-tête comme je l’ai fait, et de définir soit en haut à gauche/à droite, soit en bas à gauche/à droite de votre position.

En résumé, cela fonctionne pour moi. Alors essayez-le si vous lisez jusque-là et que rien n'a encore fonctionné. Bien que vous auriez déjà dû toucher le message original à ce jour. 

Merci Eggs, et aux autres gars avec qui vous avez collaboré pour votre Codepen.

1
Willie

"background-size: cover;" provoque beaucoup de problèmes sur tous les navigateurs mobiles, sauf Firefox!

Cela a résolu mon problème:

/* Mobile first */
body{
    background-image: url(bg_mobile.jpg);
    background-attachment: fixed;
    background-repeat: no-repeat;
}

/* Then tablets, laptops and desktops (768px and up) */
@media screen and (min-width:768px) {
body{
    background-image: url(bg.jpg);
    background-size: cover;
    }
}
1
Matthew C

J'ai eu le même problème, mais maintenant cela fonctionne . Tout ce que je devais faire était d'ajouter background-size: cover !important; et cela fonctionnait sur mon appareil Android! 

Le code entier ressemble à ceci:

body.page-id-8 #art-main {
  background: #000000 url("link to image") !important;
  background-repeat: no-repeat !important;
  background-position: 50% 50% !important;
  background-attachment: fixed !important;
  background-color: transparent !important;
  background-size: cover !important;
}

Merci beaucoup @taylan derinbay et @Vincent! 

0
Sam Gallon

C'est ce que je fais et ça marche partout :) 

.container {
  background: url(${myImage})
  background-attachment: fixed;
  background-size: cover;
 transform: scale(1.1, 1.1);

}

puis... 

@media only screen and (max-width: 768px){
   background-size: 100% 100vh;
}
0
pjdux

Voir ma réponse à cette question: Détecter le support pour l'attachement de fond: corrigé?

  • Détecter la fonctionnalité tactile seul ne fonctionne pas pour les ordinateurs portables équipés d'un écran tactile, et le code permettant de détecter l'envoi tactile par Christina échouera sur certains appareils. 
  • La réponse d'Hector fonctionnera, mais l'animation sera très agitée, il va donc sembler préférable de remplacer fixe par défilement sur des périphériques non pris en charge.
  • Malheureusement, Taylon n’a pas la bonne idée que iOS 5+ prend en charge la fixation d’arrière-plan: corrigé. Ce ne est pas. Je ne trouve aucune liste de périphériques ne prenant pas en charge les arrière-plans fixes. Il est probable que la plupart des téléphones mobiles et des tablettes n'en ont pas.
0
mattthew

Je pense que les appareils mobiles ne fonctionnent pas avec des positions fixes. Vous devriez essayer avec un plugin js comme skrollr.js (par exemple). Avec ce type de plugin, vous pouvez sélectionner la position de votre div (ou autre) en fonction de la position de la barre de défilement.

0
Héctor

Je suis en retard à la fête, mais c'est (incroyablement) toujours un problème depuis le 11.05.2017. Voici une solution simple qui fonctionnera également multiplateforme avec gradients linéaires:

.backgroundFixed {
  background: linear-gradient(160deg, #2db4a8 0%, #13af3d 100%);
  background-size: 100vw 100vh;
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  z-index: -1000;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  </head>
  <body>
    <div class="backgroundFixed"></div>
    <div class="paragraphContainer">
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
      <p>We're here to make the body scroll</p>
    </div>
  </body>
</html>

0
Tom

Le positionnement fixe est pris en charge sur mobile depuis Android 2.2 et iOS 5.

Vous devez utiliser device-with viewport sur meta et donner l'image d'arrière-plan avec quelque part avec un identifiant. Ensuite, vous obtiendrez cet identifiant avec jquery et lui donnerez une hauteur. Et bien sur 100% largeur

<html>
<head>
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #main {
          background: url(1.jpg) no-repeat center center fixed;
          -webkit-background-size: cover;
          -moz-background-size: cover;
          -o-background-size: cover;
          background-size: cover;
          width: 100%;
          overflow: hidden;
        }
    </style>
</head>
<body id="main">

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
    var hgt = $(window).height();
    $("#main").css("height", hgt)
</script> 

http://jsfiddle.net/talendil/oackpmv5/

0
Taylan Derinbay