使用位置固定时如何保持方块水平?

时间:2018-08-06 01:55:30

标签: css css-position

使用position: fixed时,浏览器将删除布局内容所具有的原始位置。如何预防呢?

在我的情况下,搜索应用栏的实际固定位置为

enter image description here

期望扮演。

enter image description here

模拟CSS代码。

.search-appbar-container {
  position: fixed;

  display: flex;
  flex-direction: row;
  align-items: center;

  width: 100%;
  height: 48px;
}

.lef-arrow-icon-container`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  width: 60px;
`;

.search-textfiled-container`
  display: flex;
  flex: 1;
  flex-direction: row;
  align-items: center;
`;

.add-icon-container`
  display: flex;
  flex-direction: row;
  align-items: center;
`;

.search-history-container {
  display: flex;
  flex-direction: column;
  justify-content: center;

  width: 100%;
  margin-top: 5px;
}
.history-toggle-button`
  position: relative;

  width: 100%;
  height: 48px;

  background-color: transparent;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;

  border: none;
  outline: none;

  -webkit-appearance: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-tap-highlight-color: transparent;
`;

.history-icon-container`
  position: absolute;
  top: 11.5px;
  left: 0;

  width: 60px;
`;

.history-text-container`
  position: absolute;
  top: 11.5px;
  left: 60px;

  display: flex;
  flex-direction: row;
  align-items: center;
`;

模拟html代码。

<div>
  <div class="search-appbar-container">
    <div class="left-arrow-container>
      ...
    </div>
    <div class="search-textfield-container>
      ...
    </div>
    <div class="add-icon-container>
      ...
    </div>
  </div>
  <div class="search-history-div">
    <button class="history-toggle-button">
      <div class="history-icon-container>
        ...
      </div>
      <div class="history-text-container>
        ...
      </div>
    </button>
  </div>
</div>

编辑

已经签出了我所有的代码,现在我可以找到发生这种情况的原因。

如果.search-appbar-container的位置为static,则history-icon-container和history-text-container的absolute位置与历史的relative位置相关-toggle-button,否则它们都与search-appear-container的fixed位置相关。

2 个答案:

答案 0 :(得分:1)

您可以将.search-history-div设置为margin-top或padding-top或设置.search-history-div {position:fixed; top:48px}

答案 1 :(得分:0)

经过我自己的搜索和尝试后,我想到了一个主意。如果要使用块级别保留固定的div,则正确的方法是在其上包装相同大小的父div。考虑到我的情况,在上search-appbar-container

中添加相同的宽度和高度包装器div
.search-appbar-container-wrapper {
  width: 100%;
  height: 48px;
}
.search-appbar-container {
  position: fixed;
  ...
  width: 100%;
  height: 48px;
}
...
<div class="search-appear-container-wrapper">
  <div class="search-appbar-container">
    ...
  </div>
</div>
...