首页 > 解决方案 > CSS:即使我更改容器的大小,如何保持自定义弹出框和用于打开它的控件之间的距离

问题描述

我正在尝试创建一种弹出框,根据它是显示在移动设备还是桌面上来改变它的位置。

我几乎设法做到了,但我无法使其可重复使用,因为如果我更改容器的大小,弹出框将不会显示在所需的位置。

这是html:

<div class="button-cont">
    <div class="input-group mb-3 button-container">
        <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
        <div class="input-group-append button-calendar" (click)="show()">
            <span class="input-group-text">.00</span>
        </div>
        <div class="custom-tooltip" #tooltip>
            Hello
        </div>
    </div>
</div>

CSS:

.button-cont {
  height: 100%;
  width: 100%;
  display:flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}



.button-container {
  position: relative;
  padding: 1rem 1rem;
  height: 3rem;
  width: 30rem;
}

.button-calendar {
  cursor: pointer;
}

.custom-tooltip {
  height: 5rem;
  background-color: white;
  width: 5rem;
  position: absolute;
  box-shadow: 0px 0px 16px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  left: 26rem;
  bottom: -93px;
  opacity: 0;

  @media(max-width: 600px) { 
     margin-left: auto; 
     margin-right: auto; 
     bottom: -86px;
     left: 50%;
     transform: translateX(-50%)
  } 

}


.show-tooltip {
  opacity: 1
}

还有我用来打开弹出框的小 Angular 代码:

import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";

@Component({
  selector: "app-ngx-bootstrap",
  templateUrl: "./ngx-bootstrap.component.html",
  styleUrls: ["./ngx-bootstrap.component.scss"]
})
export class NgxBootstrapComponent implements OnInit {
  @ViewChild("tooltip") tooltip: ElementRef;
  isOpen = false;
  constructor() {}

  ngOnInit() {}

  show() {
    if (!this.isOpen) {
      this.tooltip.nativeElement.classList.add("show-tooltip");
    } else {
      this.tooltip.nativeElement.classList.remove("show-tooltip");
    }
    this.isOpen = !this.isOpen;
  }
}

我知道组件看起来不像预期的结果,但它是我目前感兴趣的位置,这就是它应该定位的方式

在此处输入图像描述

这就是我需要的:

1)对于移动设备(已经有一个媒体查询),它应该显示在输入组下方并水平居中

2) 对于桌面版本,它应该显示在按钮(日历)下方,右侧有一点间隙。

正如我提到的它有点工作,但如果我改变input-group弹出框的大小不再正确定位。

这是stackblitz中的一个演示

标签: cssangularbootstrap-4sass

解决方案


您可以left将工具提示的 CSS 属性替换为right,这样它将随其input-group容器边界一起移动:

.custom-tooltip {
  height: 5rem;
  background-color: white;
  width: 5rem;
  position: absolute;
  box-shadow: 0px 0px 16px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  right: -15px;
  bottom: -93px;
  opacity: 0;
  ...

推荐阅读