首页 > 解决方案 > CSS 奇怪的 div 移位

问题描述

您好,我正在尝试使用电子为 i3wm 开发状态栏。
Electronjs 使用铬渲染引擎,所以我的网页应该像在 Chrome 中一样渲染。
我想设计 UI,但是当一个 div 正确放置第二个 div 垂直移动时,我遇到了奇怪的行为。

为什么这样做以及如何解决?

这是我的代码:

HTML:

<div class="module slide slide-right">
    <div class="hover-icon">
        <i class="material-icons">power_settings_new</i>
    </div>
    <div class="slider">
        <a href="" class="action">
            <i class="material-icons">settings_backup_restore</i>
            <span class="action-label"> Restart</span>
        </a>
        <a href="" class="action">
            <i class="material-icons">power_settings_new</i>
            <span class="action-label"> Wyłącz</span>
        </a>
    </div>
</div>

CSS:

* {
  user-select: none;
  box-sizing: border-box;
}

body {
  color: #ccc;
  font-family: 'Open Sans', sans-serif;
  font-size: 15px;
  font-weight: 300;
  overflow: hidden;
  padding: 0;
  margin: 0;
  background-color: #181818;
}

p {
  margin: 0;
}

a {
  text-decoration: none;
  color: #ccc;
}

a:hover {
  color: #fff;
}


.module {
  height: 50px;
  position: absolute;
  display: inline-block;
  box-sizing: border-box;
  background-color: green;
}

.slide .hover-icon {
  display: inline-block;
  padding: 13px;
  height: 50px;
  width: 50px;
  background-color: blue;
}

.slide .slider {
  display: inline-block;
  height: 50px;
  background-color: red;
}

https://codepen.io/bulion121/pen/vbBaJM

标签: htmlcss

解决方案


这里有两个问题:

1)浏览器将空格和序列解释为单个空格字符。也就是说,当浏览器看到这个时:

<div>
  a
</div>
<div>
  b
</div>

' '...它将在这两个 div 之间插入一个。有几种方法可以解决这个问题,包括font-size: 0在父容器上设置、使用 a float、使用 flexBox 以及像这样编写 HTML:

<div>
  a
</div><div>
  b
</div>

就个人而言,我会选择 flexbox。

2)因为#hover-icon#sliderinline-blocks,所以它们受 影响vertical-align。在父级div上,设置vertical-align: top.


推荐阅读