html - 没有文本的按钮元素导致后续按钮定位错误

标签 html css

我在尝试设置一个内部没有文本、只有一个字体图标的按钮样式时遇到了一个有趣的 HTML 按钮标记行为——没有文本的按钮会导致所有后续按钮都被按下。该问题仅在按钮具有 height 时出现指定的属性。

JSFiddle

<header>
    <button><!-- No text here --></button>
    <button>This button is pushed down</button>
</header>

button { height: 40px; }

起初我确定这是由于第一个按钮内的字体图标做了一些奇怪的基线魔术,但正如您从最小工作示例中看到的那样,当按钮内根本没有内容时,行为仍然存在按钮。

我可以通过向第一个按钮添加内容来解决这个问题,但因为我唯一的内容是 <span class="icon user"></span> ,这是一个字体图标,它实际上会干扰字体基线,并将按钮定位在几个像素之外。这就是为什么我决定将图标绝对定位在里面,这解决了原来的轻微定位问题,但引入了这个新问题,因为按钮现在就像是空的一样。

所以,问题仍然存在——如何避免空按钮的定位问题?

注意:以上似乎只发生在webkit浏览器上; Firefox 正确定位带有文本的按钮,但将空按钮向上推。

最佳答案

因为 button 是一个 inline 元素,默认与 baseline 对齐。

来自 W3C :

Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline.

为了正确对齐它们,使用vertical-align: top; (或middle, bottom作为值)

button { 
    height: 40px;
    margin-left: 5px; 
    vertical-align: top;
}

Demo


另一方面,您也可以使用零宽度空间实体 &#8203; - Demo


这种行为在 inlineinline-block 元素中很常见,如果你想避免上面的一切,你可以在这里使用 float,你不需要 vertical-align 属性,因为 float 也会强制 button inline作为 block 级别

Demo (使用 float: left;)

Note: If you are going with float, just make sure you clear them, if you aren't sure what clear means, than refer my answer here which will explain in detail.

关于html - 没有文本的按钮元素导致后续按钮定位错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21645695/

相关文章:

html - 使用纯 css 设计 block 引用

html - 文本在错误的地方中断

html - 为什么它不在导航栏中显示颜色?

css - Bootstrap 3 - 右侧空白

css - 文本旁边的图像填充

html - HTML,XMLNS, namespace ,XML

javascript - setTimeout回调函数不起作用

html - 导航菜单中的居中链接

php - 在此服务器上找不到请求的 URL

html - 使用Golang的HTML模板中的发件人姓名邮件