如何在视口的右端放置一个div?

问题描述 投票:0回答:2

我想将 div 定位到右侧并超出视口。它还必须响应。我只是想给 div 添加一个水平滚动动画。

出去一定要这样enter image description here

HTML:

<div class="row mt-6 bg-contact align-items-center">
      <div class="col-lg-12  h-100 d-flex flex-wrap justify-content-center" id="scrollDiv">
        <h1 class="scroll-text">CONTACT US</h1>
      </div>
</div>

CSS:我也用过bootstrap

@import url("https://fonts.cdnfonts.com/css/aquire");

body {
  overflow-x: hidden !important;
}

.contact-section div.row h1.scroll-text {
  font-size: 20cqi;
  font-family: "Aquire", sans-serif;
  white-space: nowrap;
  position: relative;
  margin-top: auto;
  margin-bottom: auto;

  -webkit-text-stroke: 3px white;
  -webkit-text-fill-color: transparent;
}
.bg-contact {
  container-type: line-size;
  background-image: url("../assets/img/contact.png");
  background-size: cover;
  background-position-y: -11rem;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: scroll;
}
html css flexbox css-position absolute
2个回答
3
投票

CSS 定位属性可用于将 div 元素移动到视口的右端。这是一个例子,

.right-div {
  position: fixed;
  top: 0;
  right: -100px; /* Change this value to adjust the distance from the right end */
  width: 300px; /* Change this value to adjust the width of the div */
  height: 100vh;
  background-color: #ccc;
}

为了相对于视口定位 div,我们在前面的代码中将 position 属性设置为 fixed。为了将 div 对齐到视口的顶部,我们还将 top 属性设置为 0。

要将 div 移出视口向右,将 right 属性设置为负值。可以更改此值以将 div 移近或远离右端。

设置 width 和 height 属性来定义 div 的尺寸。在这个例子中,我们将 height 属性设置为 100vh 以用 div 填充视口的整个高度。

你可以使用媒体查询来调整div在不同屏幕尺寸下的属性,使其响应。例如,

@media screen and (max-width: 768px) {
  .right-div {
    width: 200px;
    right: -50px;
  }
}

当屏幕尺寸小于或等于768px时,我们使用媒体查询来调整div的width和right属性

CSS 动画或JavaScript 可用于向div 添加水平滚动动画。下面是如何使用 CSS 动画的示例,

.right-div {
  /* ... */
  animation: scroll 5s linear infinite;
}

@keyframes scroll {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100%);
  }
}

我们在前面的代码中定义了一个名为scroll的CSS动画,它使div从左到右水平移动。我们在div的animation属性中使用时长5s的滚动动画,线性计时函数,无限迭代

@keyframes 规则定义了动画的关键帧,在这里我们使用translateX 函数水平移动div。 div 在 0% 关键帧处位于左端,在 100% 关键帧处移动到右端。


0
投票

正如我注意到的那样,您正试图在右侧的屏幕之外隐藏菜单或其他内容。因此,我建议使用 left:100% 而不是使用 right 定位,以确保无论 div 宽度如何,div 始终在屏幕之外:

.rightDiv {
  position: fixed;
  top: 0;
  left: 100%;
  width: 300px; 
  height: 100vh;
  background-color:#ff8800;
}

要通过单击 Hamburger 菜单或其他东西在内部设置 div 动画,您可以根据 div 的大小使用 jQuery 或 CSS 规则。我建议使用 css margin 作为最佳实践:

$(".rightDiv").animate({"margin-left":"-300px"});
© www.soinside.com 2019 - 2024. All rights reserved.