CSS: x ekseninde sabit konum ama y değil mi?


104

Yalnızca x ekseninde bir konumu sabitlemenin bir yolu var mı? Öyleyse, bir kullanıcı sayfayı yukarı kaydırdığında, div etiketi onunla birlikte yukarı kayacak, ancak yan yana değil?


3
Bu soruna bir JS çözümü verirsem sorun olur mu?
Starx

1
Bunu yapmak için javascript'e ihtiyacınız var.
LostLin

@Starx - sadece sorun değil, gerekli :-)
Pete Wilson 21

Kısa süre önce, aradığınız şeyle ilgili olabilecek benzer bir soruyu yanıtladım: stackoverflow.com/questions/8673560/…
Wex

Oldukça eski bir soruyu biliyorum ama hala bu soruyla ilgili sorunlarınız mı var?
Starx

Yanıtlar:


58

Ayrıca senaryoyu kullanan basit bir tekniktir. Burada bir demoyu da kontrol edebilirsiniz .

JQuery

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

CSS

#header {
    top: 15px;
    left: 15px;
    position: absolute;
}

Krediyi Güncelle : @ PierredeLESPINAY

Açıklandığı gibi, komut dosyasının css'deki değişiklikleri komut dosyasında yeniden kodlamak zorunda kalmadan desteklemesini sağlamak. Aşağıdakileri kullanabilirsiniz.

var leftOffset = parseInt($("#header").css('left')); //Grab the left position left first
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + leftOffset //Use it later
    });
});

Demo :)


@PeteWilson, Tamam bu çözümü kontrol et
Starx

2
leftİşlevin başlangıcındaki değeri init_left = $('#header').position()['left']veya benzeri bir şey almak hakkında ne düşünüyorsunuz ?
Pierre de LESPINAY

@PierredeLESPINAY, Evet, çok iyi bir nokta. Bu, değişiklikleri destekleyecek kadar esnek hale getirir.
Starx

2
Bu çözümü seviyorum ve sadece kendim kullandım. Bununla ilgili yaşadığım bir sorun, yumuşak kaydırma yaptığınızda (örneğin: kaydırma çubuğunu sürükleyerek) yenilemelerin biraz dalgalı olması. Görünüşe göre javascript yenilemesi css yenilemeden daha yavaş. Bunun için herhangi bir çözüm var mı?
jsarma


12

Bloğunuz orijinal olarak statik olarak konumlandırılmışsa, bunu denemek isteyebilirsiniz

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

  var $w = $(window);
  $('.position-fixed-x').css('left', $w.scrollLeft());
  $('.position-fixed-y').css('top', $w.scrollTop());

});
.container {
  width: 1000px;
}

.position-fixed-x {
  position: relative; 
}

.position-fixed-y {
  position: relative;
}

.blue-box {
  background:blue;
  width: 50px;
  height: 50px;
}

.red-box {
  background: red;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="position-fixed-y red-box">
  
</div>

The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do.

<div class="position-fixed-x blue-box">
  
</div>

DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA.

The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring.
  
 The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer.
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism).
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein.
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created.
</div>


8

Hayır, saf CSS ile mümkün değildir. Bu tür bir konumlandırma, öğeyi görüntü alanındaki sabitler. Öğeyi, diğer içeriğe müdahale etmemesi için görüntü alanının kenarlarından birine (yani üst, alt, sol veya sağ) sabitlemenizi öneririm.


7

Artık mobil, internet pazarının% 70'inin üzerinde olduğuna göre, bunu yapmak için akıllı ve duyarlı bir şey yaratabilirsiniz.

Bunu yalnızca css ile çok kolay bir şekilde oluşturabilirsiniz, bir kap için bir overflow-x: scroll ve başka bir kapsayıcı için bir overflow-y: scroll kullanın. Konteyner elemanlarını genişlik: 100vw ve yükseklik: 100vh ile kolayca konumlandırabilirsiniz.

Test etmek için örneğe orta tıklayın. Kaydırma çubuklarını görmediğiniz için mobil cihazlarda en iyi şekilde çalışır.

body{max-width:100%}
*{box-sizing:border-box;}
.container{background:#ddd;overflow-y:scroll;width:500px;max-height:100vh;}
.header{background: pink;}
.body{background: teal;padding:20px;min-width: 100%;overflow:scroll;overflow-y:hidden;min-height:300px;}
.body >div{min-width:800px;}
<body>
  <div class="container">
    <div class="header">
       Button 1 > Button 2 > Button 3
    </div>
    <div class="body">
      <div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum<br><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
     </div>
    </div>
  </div>
</body>


Alt kaydırma çubuğunun yalnızca yaya kaydırıldığında görünmesini sevmiyorum ...
Fanky

Bir mobil tarayıcıda görünmeyecektir. Chrome'da bu CSS ile gizleyebilirsiniz .yourclass::-webkit-scrollbar-track, .yourclass::-webkit-scrollbar-thumb {display:none;}. Firefox'ta bir overflow:hiddenkonteynerin dışına yerleştirerek gizleyebilirsiniz . Ama bu daha önce cevaplanmış başka bir soru, bundan eminim.
EPurpl3

2

Starx'ın çözümü bana çok yardımcı oldu. Ancak onunla dikey kaydırmalı bir kenar çubuğu uygulamaya çalıştığımda bazı sorunlar yaşadım. İşte Starx'in yazdıklarına göre ilk kodum:

function fix_vertical_scroll(id) {
    $(window).scroll(function(){
        $(id).css({
            'top': $(this).scrollTop() //Use it later
        });
    });
}

Starx'ın çözümünden biraz farklı, çünkü bence kodunun bir menünün dikey yerine yatay olarak kaymasına izin verecek şekilde tasarlandığını düşünüyorum. Ama bu sadece bir yan. Yukarıdaki kodla yaşadığım sorun, birçok tarayıcıda veya bilgisayarın kaynak yüküne bağlı olarak menü hareketlerinin dalgalı olması, oysa ilk css çözümünün güzel ve pürüzsüz olmasıydı. Bunu tarayıcıların javascript olaylarını çalıştırmada css uygulamasından daha yavaş olmasına bağlıyorum.

Bu kesiklik sorununa alternatif çözümüm, çerçeveyi mutlak yerine sabit olarak ayarlamak, ardından starx yöntemini kullanarak yatay hareketleri iptal etmek.

function float_horizontal_scroll(id) {
    jQuery(window).scroll(function(){
        jQuery(id).css({
            'left': 0 - jQuery(this).scrollLeft()
        });
    });
}

#leftframe {
 position:fixed;
 width: 200;
}   

Yaptığım tek şeyin, yatay kaydırma kesintileri için dikey kaydırma dalgalanmalarıyla ticaret yapmak olduğunu söyleyebilirsiniz. Ama mesele şu ki, kaydırmanın% 99'u dikey ve bu dalgalı olduğunda yatay kaydırmaya göre çok daha can sıkıcı.

Herkesin sabrını henüz tüketmediysem, işte bu konuyla ilgili yazım: jquery'de bir menüyü tek yönde düzeltme


2

Başlığımı / gezinme çubuğumu ortalamak ve boyut değişikliklerine duyarlı tutmak için güzel bir yol arayan bu gönderiye rastladım.

//CSS
.nav-container {
  height: 60px;  /*The static height*/
  width: 100%;  /*Makes it responsive to resizing the browser*/
  position: fixed;  /*So that it will always be in the center*/
}

//jQuery
$(window).scroll(() => {
  if ($(document).scrollTop() < 60) {
    $('.nav-container').css('top', $(document).scrollTop() * -1)
  }
})

Kaydırdıkça, çubuk ekrandan yukarı doğru hareket eder. Sola / sağa kaydırırsanız sabit kalacaktır.


Teşekkürler kardeşim. Bu işe yaradı. Yine de çok basit !! Genius you
Ram

0

Bu iş parçacığının çok eski olduğunun farkındayım ama projem için bir çözüm bulmama yardımcı oldu.

Benim durumumda, hiçbir zaman 1000 pikselden daha az olmasını istediğim bir başlığım vardı, başlık her zaman en üstte ve sınırsız doğru içeriğe sahip.

header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>

    $(window).on('scroll resize', function () {
        var header = $('header');
        if ($(this).width() < header.data('min-width')) {
            header.css('left', -$(this).scrollLeft());
        } else {
            header.css('left', '');
        }
    });

Bu, tarayıcınız başlıklarınızın minimum genişliğinden daha az olduğunda da işlemelidir


0

Sadece pozisyon ekledim: mutlak ve bu benim sorunumu çözdü.


8
Mutlak konumlandırma, öğeleri belgeye göre düzeltir. Sabit konumlandırma onları pencereye göre düzeltir. Mutlak kullanmak sorununuzu çözdüyse, başlangıçta bu soruyla aynı sorunu yaşamadınız.
Niall

0

Bu çok eski bir iş parçacığı, ancak bazı yaratıcı yerleştirmeler kullanarak buna saf bir CSS çözümü buldum. Ben jQuery yönteminin hayranı değildim ...

Keman burada: https://jsfiddle.net/4jeuv5jq/

<div id="wrapper">
    <div id="fixeditem">
        Haha, I am a header. Nah.. Nah na na na
    </div>
    <div id="contentwrapper">
        <div id="content">
            Lorem ipsum.....
        </div>
    </div>
</div>

#wrapper {
position: relative;
width: 100%;
overflow: scroll;
}

#fixeditem {
position: absolute;
}

#contentwrapper {
width: 100%;
overflow: scroll;
}

#content {
width: 1000px;
height: 2000px;
}

6
Çözümünüz, asıl pencere yerine içeriğin kapsayıcı div'inin kaydırılmasını gerektiriyor, ki bu ideal olmaktan uzaktır - kemanınız nedenini gösterir. İçeriğiniz sayfanın sağ tarafından taşıyor, ancak yatay kaydırma çubuğu ekranda değil. Bu büyük bir kullanılabilirlik sorunu.
Niall

0

Başlangıç ​​konumunu kontrol etmek için komut dosyası güncellendi:

function float_horizontal_scroll(id) {
var el = jQuery(id);
var isLeft = el.css('left') !== 'auto';
var start =((isLeft ? el.css('left') : el.css('right')).replace("px", ""));
jQuery(window).scroll(function () {
    var leftScroll = jQuery(this).scrollLeft();
    if (isLeft)
        el.css({ 'left': (start + leftScroll) + 'px' });
    else
        el.css({ 'right': (start - leftScroll) + 'px' });
});

}



0

Üst div'de ekleyebilirsiniz

overflow-y: scroll; 
overflow-x: hidden;

0
$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

Teşekkürler


0

Evet, bunu sadece CSS kullanarak yapabilirsiniz ...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

Eğer işe yararsa söyle


-1

Çok kolay çözüm:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

Bunun position:fixediçin js çözümüne gitmek yerine CSS3 kullanmalısınız
Muhammad Omer Aslam

-3

Konum kullanmanız gerektiği gibi görünüyor: sabit ve ardından üst konumu bir yüzdeye ve sol veya sağ konumu sabit bir birime ayarlayın.

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.