如何使一个HTML按钮元素始终保持在相对于页面大小的相同位置?

wdebmtf2  于 2022-10-02  发布在  Java
关注(0)|答案(1)|浏览(98)

我的网页上有一个按钮元素,我正在将其用作移动汉堡菜单。我试着让它保持在与页面大小相对的位置。

要求

  • 需要相对于页面定位,即:position: absolute; left: 90%-page-size;
  • 无法在移动设备上溢出页面

使用css可以吗?我并不反对使用一些Java脚本。

下面附上了一个代码片段。我的目标元素是一个类为hamburger-menu<button></button>元素。

body {
  overflow-x: hidden;
  font-size: large;
  margin: 0;
}

h1,
h2,
h3,
h4 {
  font-family: 'Montserrat', sans-serif;
}

.nav-bar {
  z-index: 98;
  background-color: rgba(204, 204, 204, 0.8);
  padding: 15px;
}

.nav-img {
  height: 100px;
}

.nav-options {
  text-align: right;
}

.nav-option {
  border: none;
  background-color: rgba(204, 204, 204, 0.1);
  height: 100px;
  width: 150px;
  font-size: large;
  cursor: pointer;
  transition: all 0.5s ease-out;
  position: relative;
  bottom: 15px;
}

.nav-option:hover {
  background-color: rgba(204, 204, 204, 0.1);
  color: white;
}

p,
ul,
ol,
li,
select {
  font-family: 'Poppins', sans-serif;
}

.line {
  width: 50px;
  background-color: white;
  z-index: 99;
  height: 0.5px;
}

.hamburger-menu {
  background-color: transparent;
  border: none;
  display: inline-block;
}

.mobile-nav {
  display: none;
}

.mobile-menu {
  margin: 50px;
  padding: 0;
  z-index: 98;
  position: fixed;
  right: 0%;
  bottom: -6%;
  background-color: rgba(204, 204, 204, 0.8);
  width: 100%;
  height: 110%;
  margin-left: auto;
  margin-right: auto;
  padding: 50px;
}

.mobile-options {
  position: absolute;
  list-style: none;
  top: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  height: 110%;
}

.mobile-option {
  width: 100%;
  height: 50px;
  font-size: large;
  letter-spacing: 2px;
  line-height: 100%;
  text-align: center;
  background-color: rgba(204, 204, 204, 0.8);
  border: none;
  padding-right: 60px;
}

.exit-btn {
  width: 50px;
  background-color: transparent;
  border: none;
  font-size: 4rem;
  color: white;
  font-family: 'Montserrat', sans-serif;
  font-weight: lighter;
  float: right;
  position: absolute;
  bottom: 75%;
  left: 75%;
}

@media screen and (max-width: 830px) {
  .desktop-nav {
    display: none;
  }
  .mobile-nav {
    display: inline-block;
  }
}
<div class="nav-bar">
  <nav class="desktop-nav">
    <a href="index.html"><img src="https://picsum.photos/100" class="nav-img"></a>
    <div class="nav-options">
      <button class="nav-option">About Us</button>
      <button class="nav-option">Classes</button>
      <button class="nav-option">Contact Us</button>
    </div>
  </nav>
  <nav class="mobile-nav">
    <a href="index.html"><img src="https://picsum.photos/100" class="nav-img"></a>
    <div class="nav-options">
      <button class="hamburger-menu" id="mobile-menu-enter">
                    <div class="line"></div><br>
                    <div class="line"></div><br>
                    <div class="line"></div>
                </button>
    </div>
  </nav>

</div>
9avjhtql

9avjhtql1#

你试过position:fixed;right:10px了吗?

相关问题