如何使文本与固定图像左对齐?

5

我在页面上有一张固定的图片,它总是垂直居中。它旁边是一个可滚动的文本墙,当页面加载时,我希望它总是与固定图像的顶部对齐。如下所示(红色条是如何进行顶部对齐的):

images

现在,如代码片段所示,我有一个带有 padding-top: 60pxright-div,适用于我的电脑屏幕。但是,一旦我切换到手机或平板电脑,这就不再起作用了。

我该如何使页面加载时,文本的顶部始终与图像的顶部对齐?

.left-div {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  height: 60%
}

.left-div>img {
  height: 100%;
}

.right-div {
  margin-left: 250px;
  padding-right: 10px;
  padding-top: 60px;
}
<div class="left-div">
  <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
</div>
<div class="right-div">
  <p>
    I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
  </p>
  <p>
    Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering
    injustice. It came as a joyous daybreak to end the long night of captivity.
  </p>
  <p>
    But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island
    of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful
    condition.
  </p>
  <p>
    In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to
    fall heir.
  </p>
  <p>
    This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
  </p>
</div>


你考虑过使用 background-attachment: fixed 属性来设置背景图片吗? - sol
10个回答

2
左侧图像的高度为窗口高度的60%。因此,您只需为右侧div添加20%的padding-top即可。
.right-div {
  padding-top: 20vh;
}

这是一个样例

编辑

如果你想以像素(或其他单位)设置图像高度,你可以使用CSS的calc()函数来计算填充。

.left-div {
  height: 125px;
}

.right-div {
  padding-top: calc((100vh - 125px) / 2);
}

1
你的解决方案似乎依赖于图像的高度(即60%)。如果OP更改图像的高度或者将图像高度设置为“px”而不是“%”,那么这个解决方案将无法使用。 - vrintle
将像素变体添加到答案中。 - Shant Marouti
我的意思是,px%只是举例,原帖作者可以选择任何CSS单位 - vrintle

2
你可以使用 JavaScript 来实现这个结果。
首先,使用 Element.getBoundingClientRect() 获取图像元素的顶部位置。
var image = document.querySelector('.left-div img');
var offsetTop = image.getBoundingClientRect().top;

然后将其设置为内容的上边距
var content = document.querySelector('.right-div');
content.style.marginTop = offsetTop + 'px';

此外,如果您希望您的内容在窗口调整大小时仍然保持对齐,则可以将上述语句包装在名为setTopPosition(或任何您喜欢的名称)的函数中。
function setTopPosition() {
  var image = document.querySelector('.left-div img');
  var content = document.querySelector('.right-div');

  var offsetTop = image.getBoundingClientRect().top;
  content.style.marginTop = offsetTop + 'px';
}

并且,在以下情况下调用该函数:
  • 文档完全加载时:window.onload = setTopPosition;
  • 窗口大小改变时:window.onresize = setTopPosition;
  • function setTopPosition() {
      var image = document.querySelector('.left-div img');
      var content = document.querySelector('.right-div');
      
      var offsetTop = image.getBoundingClientRect().top;
      content.style.marginTop = offsetTop + 'px';
    }
    
    window.onload = setTopPosition;
    window.onresize = setTopPosition;
    .left-div {
      position: fixed;
      top: 50%;
      transform: translateY(-50%);
      height: 60%;
    }
    
    .left-div > img {
      height: 100%;
    }
    
    .right-div {
      margin-left: 250px;
      padding-right: 10px;
      /* padding-top: 60px; is not required if the height is dynamic */
    }
    <div class="left-div">
      <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
    <p>
      I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
    </p>
    <p>
    Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of captivity.
    </p>
    <p>
    But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful condition.
    </p>
    <p>
    In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir.
    </p>
    <p>
    This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
    </p>
    </div>

    你可以在这里测试响应性

    2

    我希望这就是您要找的内容。我不知道为什么您在.left-div中添加了top:50%transform: translateY(-50%);,这会导致问题。您可以给leftright元素设置一个共同的padding-top值。

    我添加了一条红线以指示标尺,您稍后可以将其删除。

    由于您的图像顶部有9px的间隙,因此我将.left-divtop值设置为9px。当您使用无顶部间隙的图像更新时,您可以将其设置为top:0

    还需记住,p元素从浏览器中获取默认的margin-top值。为了避免顶部出现额外的间隙,您需要将其删除。在这里,我删除了第一个元素的margin-top

    #ruler{
      height:2px;
      width:100%;
      background:red;
      margin-top:61px;
      position:absolute;
    }
    .left-div {
      position: fixed;
      /*top: 50%;*/   /* Remove this line */
      /*transform: translateY(-50%);*/   /* Remove this line */
      height: 60%;
      top:9px; /* added this line */
      padding-top:60px; /* added this line */
    }
    
    
    .left-div > img {
      height: 100%;
    }
    
    .right-div {
      margin-left: 250px;
      padding-right: 10px;
      padding-top: 60px;
    }
    /*added this css*/
    .right-div>p:first-child{
      margin-top:0;
    }
    <div id="ruler"></div>
    <div class="left-div">
      <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
    <p>
      I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
    </p>
    <p>
    Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of captivity.
    </p>
    <p>
    But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful condition.
    </p>
    <p>
    In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir.
    </p>
    <p>
    This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
    </p>
    </div>


    我添加了 top: 50%; 等等的代码,因为我想要图片在垂直方向上居中。 - MarksCode
    因此,内容将始终在垂直居中位置开始。在较大的屏幕上,这不是一个好的设计。可以吗? - Ramesh
    请不要在您的帖子中添加感谢和HTH风格的消息,Ramesh - 这里更倾向于技术写作水平。谢谢。 - halfer
    1
    @halfer 已经明白了,先生。 - Ramesh

    2

    针对您的情况,您需要检查图像的宽度和顶部位置。

    以下是代码片段,它执行以下操作:

    1. 计算浮动元素的位置和宽度。
    2. 将该值应用于非浮动元素。
    3. 此处提到的颜色仅供参考。

    为了响应式设计,您需要声明在屏幕宽度范围内调用该函数(这里未包含)。

    function check(){
    var ss =$(".left-div img").offset().top;
    var w = $(".left-div").outerWidth();
    $(".right-div").css({
      "margin-left": w,
      "margin-top": ss
    });
    
    }
    
    window.onload = check;
    window.onresize = check;
    .left-div {
      position: fixed;
      top: 50%;
      transform: translateY(-50%);
      height: 60%
    }
    
    .left-div>img {
      height: 100%;
      background: #0080005c;
    }
    .right-div {
      margin-left: 250px;
      padding-right: 10px;
        background: #ff000040;
    }
    .right-div > p {
      margin-top: 0px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="left-div">
    <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
     <p>
      I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
    </p>
    <p>
      Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering
      injustice. It came as a joyous daybreak to end the long night of captivity.
    </p>
    <p>
      But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island
      of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful
      condition.
    </p>
    <p>
      In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to
      fall heir.
    </p>
    <p>
      This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
    </p>
    </div>

    希望这对你有用:) 此外还附上了codepen演示。

    1

    您可以使用Javascript / Jquery来实现此结果,因为大部分计算必须动态完成。

    我使用Jquery和CSS实现了这一点。以下是我考虑实现结果的要点:

    1. 计算.left-div从窗口(顶部)的距离。
    2. 计算应用于body的边距(浏览器默认值)
    3. 将上述步骤中新计算的padding-top值应用于.right-div
    4. 删除应用于p元素(浏览器默认值)的margin-top
    5. 即使在调整浏览器大小时也保持文本与图像的对齐方式。

    结果链接:https://jsfiddle.net/Baliga/1qsfuo6b/28/


    0
    你是在寻找类似这样的东西吗?不过这里需要一些改进。
    <html>
          <head>
              <style>
                .main{
                  min-height: auto;
                  max-width: 2000px;
                  margin: auto;
                  border:3px solid black;
                  display: grid;grid-template-columns: 1fr 3fr;
                }
                .imgC{
                  position: relative;padding-right: 100%;
                }
                @media(max-width:900px){
                  .main{
                    grid-template-columns: 1fr;
                  }
                  .imgC{
                    padding-right: 0px;padding-bottom: 100%;
                  }
                }
                @media(min-width:900px){
                  .main{
                    grid-template-columns: 1fr 3fr;
                  }
                  .imgC{
                    padding-bottom: 0%;padding-right: 100%;
                  }
                }
              </style>
            <title></title>
          </head>
          <body>
            <div class="main">
                <div class="imgC">
                  <img style="position:fixed;" src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
                </div>
                <div style="float: right">Lorem ipsum dolor sit amet consectetur adipisicing elit. At, laudantium totam aut distinctio unde a perspiciatis dignissimos corporis saepe tempora mollitia harum perferendis magnam ipsam voluptates! Autem inventore facere ab modi, rerum culpa iste dicta veritatis eius enim sint, temporibus quisquam sit minima voluptas doloribus non maxime assumenda tenetur quas. Quia odit dolorem sit maxime enim, voluptas doloribus nemo, commodi facilis soluta molestiae vero ea esse. Nulla esse explicabo qui eveniet libero dicta labore ipsum repellat iusto blanditiis ea minima autem reprehenderit, aliquam rem, quidem alias, architecto iste! Explicabo eligendi, consequatur quam, deleniti voluptates inventore illo sit, voluptate quis nihil sequi accusamus! Placeat minima qui rerum voluptatem! Hic porro, illum mollitia eum consequuntur saepe non esse officia itaque fuga. Velit veniam inventore recusandae totam, id quidem quae optio placeat dolor eaque cumque iure! Aliquid dolores libero sequi doloribus, quae ipsum perspiciatis dicta quas excepturi doloremque blanditiis debitis nemo esse maxime ipsa rem veniam illum iusto, ipsam possimus voluptate, quidem maiores ut animi! Quis, doloremque voluptatum! Ex similique assumenda quam quidem facere vero blanditiis sit, eum quaerat commodi perspiciatis magnam sunt asperiores. Sequi quasi deserunt veritatis perspiciatis eligendi id corrupti! Adipisci, expedita eligendi non itaque voluptate qui quas eum quae, asperiores autem, quo at ipsum! Velit repellendus qui explicabo eum reprehenderit deleniti iste enim quia asperiores! Odit harum autem earum. Sunt illo ducimus nisi quod voluptatibus dolorem. Sunt facere expedita excepturi quia similique distinctio velit debitis ipsa dolores tenetur a repellat voluptas fugit quae sint sequi, tempora provident maiores accusantium laborum labore non? Minima necessitatibus nam nulla! Nisi sequi sed cumque suscipit, qui officia tempora commodi quaerat numquam modi enim alias impedit quos quam odio aliquid accusantium eos. Minima quo, fugit optio minus recusandae quisquam quasi culpa molestias sapiente in atque voluptates a eveniet maiores! Iste eum minus, voluptatem quia maiores nam beatae? Ratione alias amet itaque vel aperiam id molestias recusandae iste nam porro voluptas unde aspernatur deleniti eum iusto excepturi, sit delectus saepe! Quae enim voluptas error nemo fugit minus nulla magnam! Provident quis nam, illum voluptatum alias sequi eius iste veritatis magni cupiditate incidunt! Pariatur ab blanditiis aspernatur, vel debitis saepe sint tempora perspiciatis quis fugiat in dignissimos quos nemo! Accusamus, provident distinctio porro, hic ipsum saepe quibusdam reiciendis sint corrupti ratione obcaecati nesciunt. Obcaecati minima facilis earum iusto quo. Architecto nesciunt mollitia, omnis velit magnam exercitationem corporis, illum corrupti placeat accusantium ex consequatur? Nesciunt quas placeat porro cumque tempora quae aliquam provident, nostrum, quod ullam ab, consequuntur perferendis sit nulla harum dolor aut ducimus esse iusto distinctio qui amet eius? Earum vel esse dolorum sit praesentium sapiente deserunt facilis eius tempora veniam dolores reprehenderit repellendus asperiores quisquam, eos officiis possimus quia? Tenetur tempora, fuga et corporis, commodi, repellendus eius provident quo porro veniam soluta quaerat consequuntur fugit. Odit aut a, exercitationem adipisci facere tenetur earum dolores voluptates veritatis. Commodi non deleniti ducimus officiis odio fuga, recusandae quae dolorum praesentium. Dolorum est quo debitis nihil rerum! Aliquam, aut tempora fugiat ipsum soluta, quisquam ex quo totam adipisci quod nam delectus, sed illum dignissimos consectetur vero? Dolorum consequatur quis quisquam, rem nisi rerum assumenda itaque aperiam unde earum non culpa soluta consequuntur et nihil suscipit dolor libero dicta deleniti laudantium tenetur aliquam, porro, similique dolores! Quidem sed facilis commodi id laudantium blanditiis? Eum blanditiis, velit praesentium, ad magni aut ducimus dolore, iure maiores deleniti saepe eaque delectus? Numquam hic nisi sint odio consequuntur alias inventore facere impedit commodi eius, laboriosam aliquam quod repellendus aliquid placeat quia quasi itaque illum ipsum quaerat explicabo accusamus sit? Ut doloremque reprehenderit, illo itaque provident dolorum repudiandae voluptatibus sit ducimus atque voluptates odio ad at iste expedita beatae exercitationem, aut, fugit sequi tempora enim. Voluptas quis repellat quibusdam excepturi tempora dolor ipsa vero assumenda veniam qui ea, illum laboriosam accusantium ratione recusandae nobis. Cum molestias odit aliquam ea, minima eius rem officia praesentium natus laboriosam. Et quo corrupti laborum enim cum necessitatibus ratione culpa nam in voluptate animi qui voluptas, rem tempore. Ad magni fuga blanditiis voluptate unde, nulla, corrupti eum accusantium inventore deleniti odio. Fugiat quisquam suscipit magni, exercitationem eius explicabo. Ea recusandae dolorem cum nisi, voluptatum non blanditiis voluptas totam ullam unde ducimus vero modi dolores, facilis nihil at reiciendis et ipsa ipsum aliquid quae! Rem libero fuga ipsum rerum quidem qui sit odit quae natus. Nesciunt eum perferendis natus accusamus quasi sed, vitae ducimus ea fugit autem voluptatibus. Facere suscipit odit consequuntur, harum architecto labore et nesciunt sunt minus voluptates asperiores fuga praesentium neque ad magnam assumenda a laborum exercitationem accusamus illo recusandae, fugiat vitae? Necessitatibus aliquid porro voluptatibus vero sunt eligendi neque voluptas architecto debitis voluptates obcaecati ullam, nobis id tempore dignissimos error! Quaerat, nisi nam corporis, tempore reiciendis quasi animi rerum quisquam alias obcaecati enim sapiente consectetur, commodi expedita assumenda amet illo aperiam error veritatis hic quod fuga! Tempore hic, nesciunt aspernatur labore magnam eligendi placeat minima recusandae, exercitationem quod necessitatibus. Sequi facere illo quo ullam nostrum quaerat! Provident, dolor nemo perferendis quae, soluta aliquid eveniet nesciunt dolorem molestiae quas tenetur non dolores. Sint et velit incidunt quam porro fugit adipisci impedit, unde qui ex quasi eaque molestiae ipsa laudantium nam delectus deserunt nemo laborum in quos ducimus? Illo aperiam delectus laboriosam magnam soluta quas aut? Quasi ex dolore dolorum itaque ducimus cumque, aut repellendus neque, dolor necessitatibus libero, delectus laudantium ipsum animi commodi impedit vel voluptatum ad quidem. Quas placeat dolor labore animi beatae velit minima assumenda cumque tempora rerum repudiandae, sit impedit unde. Rerum obcaecati harum, non dolor culpa placeat, possimus minus qui deleniti dolorum, eos adipisci. In similique voluptates voluptate atque facilis doloremque, dolorem, sint esse dolor ex molestiae, dignissimos animi. Dolorum quis eaque dicta vero fugit, at molestias omnis quasi in saepe. Ut explicabo sapiente nulla error, recusandae ab rem aperiam impedit. Saepe alias praesentium animi quae nihil tempora corrupti porro iste omnis qui. Amet eos deserunt aperiam repellendus quasi illo deleniti autem? Ex, earum incidunt. Laboriosam esse tempora, neque voluptas natus itaque iure beatae. Facere molestias voluptatibus quam sequi commodi nulla aliquid sit vitae, nam exercitationem ex ut officiis. Nihil magnam numquam reprehenderit, eaque, modi eligendi repellendus temporibus maxime id neque, eum at! Eos repellendus quo quidem magnam reiciendis illo aut adipisci dolore vero maiores? Natus velit voluptate tenetur aliquid, facilis eaque ex quisquam atque similique doloribus minus ullam nulla possimus vero ipsam quaerat veniam cum placeat, asperiores fugit voluptatem. Temporibus modi ab est corrupti. Eum saepe, illum, neque, rerum aspernatur delectus quia recusandae veniam magnam nobis similique labore officiis harum reprehenderit quae libero unde. Animi commodi fugiat possimus numquam, repellat consequatur repudiandae recusandae culpa! Harum, ad libero hic vel voluptatibus assumenda eius velit aperiam rem natus consectetur quos nulla molestias earum? Voluptatum quasi officiis commodi numquam. Reiciendis necessitatibus et laudantium qui voluptates. Quidem deleniti, culpa consectetur maxime in odio sint. Dolorum accusamus id, suscipit saepe praesentium odio neque magni error labore assumenda corporis, sit ipsum consequuntur maiores at harum quasi unde eligendi libero illum, vero laborum quidem laboriosam maxime! Nihil eum ut libero reprehenderit fuga eligendi deleniti placeat odio, accusamus beatae illum labore molestias accusantium consectetur quo voluptatum nam impedit officia expedita, sunt alias ex voluptatibus. Eius earum architecto fugiat harum facilis voluptatum autem, et odio sunt cumque consectetur minus explicabo, commodi deleniti a eligendi reprehenderit ratione molestias necessitatibus quis? Sapiente culpa nisi temporibus vel officia? Vel numquam saepe sequi nam quas facilis ducimus unde ipsum, ut quia quasi repellendus ipsa? Dignissimos necessitatibus excepturi rerum, voluptatibus quis dolorem, debitis dolorum delectus provident cum, recusandae deleniti? Sed ratione, officiis necessitatibus accusamus alias natus veritatis eveniet dolorum quia ullam iste numquam modi sit nobis distinctio vero impedit amet, consequuntur cupiditate voluptatum nihil. Nostrum itaque, recusandae libero incidunt deserunt ipsa, autem nam fuga, vel eum laborum neque dolorum facilis similique ab? Asperiores repellat modi esse a impedit vel eum accusamus obcaecati optio officiis animi, molestiae incidunt facere assumenda ipsum est numquam iste perferendis consequatur natus dignissimos nam sunt deserunt doloribus. Numquam voluptas recusandae cumque rerum aliquid earum, harum laudantium, quisquam deleniti corrupti corporis error provident? Delectus amet totam odio, dignissimos alias iste aliquam nesciunt facere? At quae voluptatibus laborum velit assumenda vero illo est beatae voluptatem ipsam dicta libero dolorum ducimus facilis quaerat sint dolorem officiis possimus, inventore eius. Non dolorem beatae voluptas perspiciatis quam illum officiis saepe assumenda facere, sunt atque vero corrupti nesciunt quidem ratione sed optio rem blanditiis sit officia. Quo, exercitationem placeat! Ratione, ducimus voluptate. Dolorum illum tempore consequatur rem, eaque dolores earum reiciendis beatae cupiditate veniam quisquam maiores, pariatur necessitatibus dignissimos mollitia dolore adipisci consequuntur reprehenderit? Saepe, alias porro reprehenderit corporis velit, doloribus nisi dolore labore expedita eaque veniam. Quam dignissimos porro perspiciatis rerum libero. Possimus temporibus a repellat pariatur iusto itaque doloremque omnis laudantium, tenetur eos. Eveniet, dolor vitae? Quam accusantium iure commodi, itaque ullam repellendus consequatur atque, nam consequuntur voluptatum, voluptates facilis animi impedit. Ut dolore, totam quidem culpa dignissimos ex maiores nihil! Praesentium reiciendis mollitia animi eligendi error iste natus. Magni repudiandae cupiditate quae minima ullam debitis illo quisquam, inventore voluptas id atque. Ea ipsa repellendus quo dolores repudiandae tenetur nihil, facere sunt neque. Quae voluptatibus voluptate perferendis reiciendis, sint animi, vitae ipsum iste eveniet velit deserunt vero sit asperiores tempore ad fugiat. Nesciunt harum accusamus maxime id ipsa magni, tenetur aut fugiat optio minus, debitis laudantium quis odit molestiae nisi molestias, et voluptas ullam dolorem assumenda dolore ducimus doloribus? Corrupti molestias, impedit reiciendis tenetur praesentium ipsa deserunt architecto quia delectus excepturi, nam dicta quibusdam a quisquam modi dolor blanditiis, quos amet. Mollitia voluptatem non, ipsum, consequatur nulla ea quod voluptate dolorum ex quas enim. Labore dolorem nam perspiciatis, dolores architecto deleniti. Doloremque esse ipsam accusamus neque deserunt nam illo laborum atque cupiditate error odio, placeat commodi quasi explicabo aspernatur iste nostrum. Suscipit esse nam odit, corrupti ea harum dolore corporis impedit fugit non, provident consectetur. Perspiciatis saepe aut voluptas nostrum. Veritatis est sint eaque numquam ea, similique, recusandae asperiores illo nesciunt explicabo doloremque voluptate? Autem possimus hic at, pariatur dicta esse, commodi beatae dolorum enim voluptatibus nihil porro ratione dolor voluptas minima amet libero cupiditate, repellendus modi omnis quod illo incidunt nam magni! Assumenda quis iure ut vel expedita fuga id enim dolor? Libero quae molestiae veniam architecto impedit iste deserunt eum rem officia commodi necessitatibus accusantium provident dignissimos sunt, asperiores repellat molestias numquam nemo velit dolore eveniet accusamus! Accusamus at recusandae, quos explicabo quisquam illo ullam voluptatem voluptatum dolore, molestiae cupiditate expedita eveniet praesentium perspiciatis rerum id commodi? Delectus, repudiandae. Accusantium repellat id earum aspernatur doloremque doloribus, temporibus, ad nobis vero hic distinctio atque assumenda? Sed, minus vitae corporis id libero esse possimus eius, deleniti voluptas animi eligendi? Vero inventore odio deleniti vitae reiciendis quidem natus provident, sequi similique ducimus doloremque, temporibus animi distinctio quisquam perspiciatis. Eum, blanditiis cupiditate enim accusantium aperiam quidem, minima quaerat illum assumenda suscipit earum, tempora eius quam fugiat. Fuga porro quae illum et sequi! Eos neque quibusdam vel assumenda molestiae laudantium vero, veritatis recusandae alias enim. Aperiam repellendus suscipit officiis deserunt, aspernatur fuga autem dolor. Reprehenderit nemo totam quibusdam dignissimos excepturi architecto, quas vel doloribus voluptates similique fugiat, accusantium nihil eligendi fugit natus recusandae, quia culpa repellat. Itaque nostrum saepe fuga accusantium ducimus magni. Aliquid quis officiis nemo porro maiores facere sunt laborum similique quo numquam beatae natus, pariatur mollitia dicta corporis incidunt! Quisquam tempora voluptatem consequatur ducimus deserunt sit corporis ullam consequuntur inventore, aperiam nam recusandae sed dolor rerum nihil, libero tempore. Accusantium quidem, necessitatibus quae ipsam vero nulla repellat quam doloribus explicabo? Dignissimos voluptas enim maiores temporibus dolorem magni soluta architecto est quaerat totam incidunt delectus ullam aut quos earum esse exercitationem, recusandae consectetur! Repellat, soluta beatae maiores repudiandae, nostrum nobis rem necessitatibus veritatis vitae hic facere atque eaque, laudantium quasi odit cupiditate et aperiam! Labore iusto aspernatur maiores distinctio quos soluta, repellat accusantium sequi temporibus nobis cumque consequuntur. Perspiciatis harum magnam vero a, aut quae illum voluptatum id similique cumque dicta. Odit, sint minus consectetur neque eum optio molestias omnis error incidunt natus veritatis adipisci, necessitatibus facere quisquam, blanditiis veniam aperiam porro nobis laborum sequi? Eius nemo quae eligendi sed dolor nobis reiciendis ducimus distinctio, tenetur accusamus! Atque quis velit explicabo suscipit sit asperiores amet corrupti, dolores culpa quae architecto odit commodi quos repellat autem impedit ab pariatur itaque molestias et, dolorem aliquid? Sit, quas fugiat. Iusto maiores placeat alias voluptatibus cupiditate debitis atque quasi, aspernatur doloribus impedit corporis minus culpa aut ab beatae mollitia error at dolore rerum explicabo similique ratione autem. Velit totam dolore, magni praesentium dolor nihil neque amet minima consectetur nam assumenda, provident sequi facilis odit nemo maxime veniam aliquam eos impedit dignissimos incidunt id. Accusantium dolor ea distinctio autem earum numquam labore, sit harum placeat laboriosam nostrum voluptates commodi vel voluptatibus laudantium quisquam sunt minima, cupiditate vitae! Voluptas repudiandae nostrum inventore nemo voluptatum molestias voluptate adipisci nisi nulla corrupti quas, esse harum vero optio. Delectus nam pariatur eos accusantium reiciendis vero rem dolore, provident nulla rerum adipisci porro cumque officiis minima harum voluptatum voluptatem veniam animi quisquam laboriosam soluta, magni itaque! Amet, velit asperiores reprehenderit quam quia molestiae alias excepturi, sit, esse rem libero! Nisi quisquam atque exercitationem deleniti aliquid nesciunt dignissimos expedita, suscipit, alias laudantium explicabo saepe inventore pariatur earum enim est! Voluptatibus velit aliquam laudantium ipsam voluptatum est facere minima amet laborum ea exercitationem, pariatur ipsa officia natus ab voluptate hic, modi perspiciatis? Ipsam repudiandae quibusdam laboriosam eligendi, rem cum expedita quod aliquam est delectus consequuntur perspiciatis quidem doloribus maxime consequatur voluptatum dignissimos! Quia saepe tenetur totam placeat eveniet aperiam similique natus eum cupiditate sunt ullam soluta expedita vitae corrupti inventore molestiae vel possimus voluptatibus voluptatum, neque ab provident labore omnis iusto! Distinctio in voluptatem suscipit culpa nobis enim consectetur ab magni iusto. Sapiente id beatae earum! Quod, asperiores qui ipsa aliquam molestias facere totam porro rem! Praesentium, enim. Dignissimos beatae, corrupti, sint nisi ullam molestiae adipisci tempora velit quas debitis reiciendis. Deleniti inventore illum qui unde molestias quibusdam consequatur atque expedita officia iure voluptatum, facere sequi dolorem quam eos laborum eligendi molestiae aspernatur ducimus quas fugiat rerum mollitia suscipit. Suscipit corrupti nostrum sit animi, vitae facere a temporibus, exercitationem dignissimos, illo at vero tempore hic iure quisquam nobis! Modi corrupti ex voluptates. In corporis accusantium a dicta autem! Vel possimus facilis deserunt iusto expedita, labore sed id modi iste ad quidem ratione nam accusantium architecto perferendis non magni minima, consequuntur totam assumenda omnis eaque. Perferendis ullam placeat debitis ipsam, sunt magni. Fugiat nemo iste ea numquam animi possimus mollitia unde. Magnam eius obcaecati hic officiis soluta accusantium unde repellat. Blanditiis, placeat. Cupiditate eum veniam blanditiis minima labore eaque iure quod cum? Alias eligendi quis officia, libero, molestias in a illo inventore excepturi harum optio iure sed est reiciendis sapiente qui, perferendis natus maiores possimus quidem enim nihil porro? Voluptatibus similique libero reiciendis, laborum quibusdam cupiditate laudantium soluta, corporis fuga quis doloremque vel, blanditiis omnis beatae nam voluptatem veritatis natus distinctio? Id quos molestias quam iure, distinctio saepe doloremque odit! Similique rerum numquam debitis ipsam repudiandae enim. Beatae tempora praesentium vitae. Modi error eum ex rem ut est expedita provident vel, sapiente ducimus dolore exercitationem. Officiis deserunt harum atque similique dolores? Numquam quod maxime nostrum id autem quidem quas in amet impedit, asperiores consequuntur dolores nihil ut voluptatum ipsa at sunt mollitia reprehenderit earum. Incidunt laboriosam assumenda a id eligendi ad quaerat perferendis pariatur doloribus necessitatibus. Quos temporibus architecto enim beatae saepe cupiditate dolores debitis ratione quaerat dolore, cum eos ab harum autem deserunt, id obcaecati nesciunt totam sed nobis est, voluptatibus amet laborum veritatis! Quis ad neque a ea eveniet? Numquam a facere quam neque, quasi recusandae dicta velit autem quas mollitia. Adipisci in qui at accusantium tempora facere provident ut animi veritatis voluptatem blanditiis reiciendis laborum nam, nostrum quia itaque. Molestias minima dolorem libero voluptate? Fuga molestiae, quae nesciunt, voluptas accusantium consequatur error nobis et quam earum nemo! Aspernatur deleniti quam doloremque dolore eligendi dolor quisquam suscipit deserunt exercitationem repudiandae nemo natus nesciunt facere sequi ea quibusdam labore sed, distinctio inventore illo ducimus expedita! Ea fugit, repellendus voluptates mollitia quae molestias consequatur voluptatum beatae quam, atque sed in rem veniam amet explicabo ut dignissimos ad, laboriosam rerum accusamus quis? Tempore suscipit eveniet, adipisci et quos velit facere illo libero corporis earum unde, veritatis ad ducimus aspernatur nesciunt iure magni, odit voluptatem necessitatibus officiis exercitationem nulla aliquam? Error laborum enim voluptas dolorem aperiam? Sunt eaque officia repellat? In deserunt iste quam saepe eaque, cum officiis magni blanditiis? Rem vel necessitatibus aut beatae magni architecto vitae corrupti minus voluptate, quo expedita, maiores distinctio recusandae quam! Assumenda repellendus debitis non blanditiis est itaque, obcaecati architecto ut dicta neque nulla corrupti, odio maiores fugiat. Consequuntur molestias inventore quaerat. Aut laudantium dolorum sint ipsam modi itaque nihil animi officiis nesciunt iure esse id sunt fugiat, mollitia odio quisquam! Repellendus animi quas id unde est possimus officiis expedita saepe quo, suscipit totam ea ad corrupti, quisquam ut pariatur eaque magnam inventore minus tenetur hic, voluptates itaque iste. Nobis modi unde blanditiis. Aliquid aspernatur sapiente officia est exercitationem quis sint voluptate quam quaerat laborum ducimus sequi soluta aliquam error porro quod rerum, qui veritatis iusto hic excepturi sit corrupti. Tenetur reprehenderit cupiditate, suscipit ad ducimus placeat laborum vel quibusdam molestiae. Porro voluptas tempora temporibus ducimus, ratione placeat tempore numquam eligendi est doloribus, obcaecati magni impedit. Eius in fugit atque nisi officiis pariatur nemo doloremque, ullam vel. Provident dolorem, illum aliquam suscipit facere ullam consectetur! Impedit quae rerum perspiciatis explicabo nostrum sint voluptatum in, laudantium voluptatibus aspernatur soluta dolores? Sed nam blanditiis vero natus eveniet soluta maxime fugiat rerum corporis earum, odit quaerat dicta ad error quasi? Iusto vitae fugit hic! Eveniet nostrum iusto vero omnis inventore? Voluptate dolorum non minus porro esse aliquam sed ratione itaque! Aliquid dolores illum quae inventore consequatur architecto laboriosam eaque, exercitationem, temporibus fugiat voluptatem quos. Quae quas dolores praesentium quisquam, sed eligendi harum facilis, ut possimus, provident atque animi maiores alias deleniti saepe adipisci ipsum sunt voluptate qui expedita nostrum explicabo facere! Dolorem, asperiores harum voluptatem eaque porro maiores. Corrupti reiciendis, soluta illum, sunt repellat, corporis provident nihil vel minima modi nostrum. Accusantium necessitatibus tenetur est nemo? Eos, magnam obcaecati inventore tempora labore est dolores dolor soluta blanditiis voluptatum quis modi ratione consequatur eligendi impedit nisi quam vel recusandae reiciendis non quae repudiandae? Quod iure iusto, blanditiis itaque ipsum delectus nostrum labore facilis quo sit vero corrupti doloremque voluptatum asperiores maxime ut quibusdam aut eos officiis cumque praesentium. Doloribus provident, doloremque libero rerum sequi aliquid beatae, dolore, mollitia repellendus suscipit ipsum odio. Earum ad voluptatum esse ut tenetur saepe, adipisci, exercitationem sit explicabo alias reiciendis rem minus et? Placeat perferendis tenetur hic reiciendis inventore! Veritatis officiis iure facere esse voluptas explicabo autem, illo temporibus.</div>
            </div>
          </body>
        </html>
    

    0
    晚了一些,但还是来了。
    由于你不会将其用作“可用”代码的机会很小,所以我稍微扩展了功能,但你可以根据需要剥离部分。例如,我编写了一些JavaScript,如果您滚动过去,它会固定图像,而不是从一开始就固定图像。该代码允许您将其放置在文档中的后面,而不是在页面顶部。
    margin-left:250px来看,我只能假设您希望图像的最大宽度为250px。
    以下是更新后的代码。
    HTML
    <div class="container">
      <div class="left-div">
        <div>
          <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
        </div>    
      </div>
      <div class="right-div">
        <p>
          I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
        </p>
        <p>
          Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering
          injustice. It came as a joyous daybreak to end the long night of captivity.
        </p>
        <p>
          But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island
          of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful
          condition.
        </p>
        <p>
          In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to
          fall heir.
        </p>
        <p>
          This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
        </p>
      </div>
    </div>
    

    CSS

    * {
      box-sizing: border-box;
    }
    
    html,
    body {
      margin: 0;
      padding: 0;
    }
    
    .container {
      display: flex;
    }
    
    .left-div {
      width: 250px;
      flex: 0 0 auto;
    }
    
    .left-div div,
    .left-div img {
      width: 100%;
    }
    
    .right-div {
      flex: 1 1 auto;
    }
    
    .left-div div.fixed {
      position: fixed;
      top: 0;
      width: 250px;
    }
    
    p:first-of-type {
      margin-top: 0;
    }
    

    JavaScript

    $(document).on('scroll', function() {
      scrtop = $(window).scrollTop();
      offtop = $('.left-div').offset().top;
      if (scrtop > offtop) {
        $('.left-div div').addClass('fixed');
      } else {
        $('.left-div div').removeClass('fixed');
      }
    });
    

    这里有一个可用的代码片段: http://jsfiddle.net/scooterlord/Lyxfu30h/


    这个问题可以在不使用JavaScript和更多复杂性的情况下解决。 - Igwe Kalu
    显然,但这很大程度上取决于提问的方式。这段代码不可能完全按原样用于页面顶部,所以我编写了这段代码。 - scooterlord

    0

    这个问题没有必要使用 JavaScript 来解决。首先,我们将这两个 div 包裹在另一个 div 中,这样我们就可以在其上使用 flex box。

    我们使用 flexalign-items:start;,以便所有内容都在同一行:.wrapper{ display:flex; align-items:flex-start; }

    我们在 wrapper div 中给我们的 divs 设置 flex:1;,这样它们两个的宽度相等;

    调整图片的宽度和高度,并使用 object fit:contain 属性,使图像不会被拉伸或出现奇怪的情况。

    最后,给左侧的 div 添加 position:sticky;top:0;,这样当您滚动时,图像将跟随您,直到您到达底部。

    但是,请确保对该图像进行一些裁剪,以获得最佳效果。

    请查看下面的片段,并告诉我是否适用于您。

    .wrapper{
      display:flex;
      align-items:flex-start;
    }
    .wrapper > div{
      flex:1;
      
    }
    
    .wrapper > div p {
      margin-top: 0;
    }
    
    .left-div>img {
      height: 100%;
      width: 75%;
      object-fit: contain;
    }
    
    .left-div{
      position: sticky;
      top :0;
    }
    <div class="wrapper">
    <div class="left-div">
      <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
      <p>
        I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
      </p>
      <p>
        Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering
        injustice. It came as a joyous daybreak to end the long night of captivity.
      </p>
      <p>
        But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island
        of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful
        condition.
      </p>
      <p>
        In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to
        fall heir.
      </p>
      <p>
        This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
      </p>
    </div>
    </div>


    0

    我不会用锤子去杀蚊子。虽然Javascript可以做很多事情,但你并不需要它来解决这个问题。

    这个问题可以通过CSS干净地解决。以下是如何实现的,其中样式代码中包含了解释:

    html,
    body {
      width: 100%;
      height: 100%;
    }
    
    /*
    The parent of both sections -- in this example, it's the
    `body` element
    */
    body {
      padding: 0;
      margin: 0;
    }
    
    .left-div,
    .right-div {
      /*
     Maths: if height of left-div is 60 and you want the block
     to be centered vertically, then top and bottom
     should be displaced by 20 each.
     
     Moreover, since you want both left and right sections to be
     initially aligned at the top then it makes sense to set this
     property commonly.
     */
      top: 20%;
    }
    
    .left-div {
      /* Some colour to make the section stand out */
      background-color: red;
      /* ---------- ---------- ---------- */
      position: fixed;
      height: 60%;
    }
    
    .left-div>img {
      height: 100%;
      /*
     to avoid surprises, you may want to take control of the
     properties below rather than leave them to be determined
     by the user-agent
     */
      border-image-width: 0;
      padding: 0;
      border: none;
      margin: 0;
    }
    
    .right-div {
      /*
     It looks like you don't want the top padding here,
     so it goes in the bin.
     */
      margin: 0;
      padding: 0;
      /*
     `top` property requires a position to be specified
     other than the default `static`.
     
     Using `relative` to meet your requirement would demand
     that the parent element be should have no top border/padding.
     */
      position: absolute;
      /* ---------- ---------- ---------- */
      margin-left: 250px;
      padding-right: 10px;
      /* Some colour to make the section stand out */
      background-color: yellow;
    }
    
    .right-div p:first-child {
      /*
     This is one of the main issues!
     A <p> element by default comes with a margin set by the user agent
     */
      margin-top: 0;
      padding-top: 0;
    }
    <div class="left-div">
      <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
      <p>
        I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
      </p>
      <p>
        Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering
        injustice. It came as a joyous daybreak to end the long night of captivity.
      </p>
      <p>
        But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island
        of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful
        condition.
      </p>
      <p>
        In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to
        fall heir.
      </p>
      <p>
        This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
      </p>
    </div>


    -1

    使用CSS网格将div顶部填充60像素,将左侧div(section)中的img固定,从右侧div(aside)中删除顶部边距,使用浮动和填充进行样式设置。

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>test</title>
    
    <style>
    .left-div {
      float: left;
      grid-area: section;
    }
    .left-div > img {
        position: -webkit-sticky;
        position: sticky;
        max-width: 60%;
        top: 60px;
        margin-left: 15%;
    }
    .right-div {
      float: right;
      max-width: 60%;
      padding-left: 10px;
      grid-area: aside;
    }
    .holder {
      padding-top: 60px;
      display: grid;
      grid-template:
        'section aside';
    }
    .begin {
      -webkit-margin-before: 0em;
      padding-top: 0em;
      margin-top: 0em;
    }
    </style>
    </head>
    <body>
    <main class=holder>
    <div class="left-div">
      <img src="https://cdn1.iconfinder.com/data/icons/apple-products-icons/100/apple-outlined_iphone_6-2-512.png">
    </div>
    <div class="right-div">
    
    <p class=begin>
      I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
    </p>
    <p>
    Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of captivity.
    </p>
    <p>
    But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. So we have come here today to dramatize an shameful condition.
    </p>
    <p>
    In a sense we've come to our nation's Capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir.
    </p>
    <p>
    This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.
    </p>
    </div>
    </main>
    </body>
    </html>
    

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