微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 按钮位置绝对不能按预期工作

任何人都可以解释为什么按钮不是绝对定位到右边?我希望它从每个边缘都是3px.

HTML

<div class="wrapper">
    <button>Hello world</button>
</div>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    background-color: #f33;
    position: relative;
}

.wrapper button {
    position: absolute;
    top: 3px;
    bottom: 3px;
    left: 3px;
    right: 3px;
}

此外,该按钮如何能够垂直对齐其内容

解决方法

与大多数表单元素一样,button是一个替换元素.当绝对定位时,替换元素的行为与常规非替换元素(例如div)的行为不同.适用于 section 10.3.8 of CSS2.1的以下两点:
  1. The used value of ‘width’ is determined as for inline replaced elements. If ‘margin-left’ or ‘margin-right’ is specified as ‘auto’ its used value is determined by the rules below.

  1. If at this point the values are over-constrained,ignore the value for either ‘left’ (in case the ‘direction’ property of the containing block is ‘rtl’) or ‘right’ (in case ‘direction’ is ‘ltr’) and solve for that value.

与未替换的元素不同,按钮的宽度不是基于指定的偏移量确定的,而是由按钮本身的内容决定的.由于宽度的使用值不是自动的,并且左侧和右侧的指定值不是自动的,因此值过度约束并且强制浏览器向右忽略以便考虑宽度.

如果希望按钮填充包装的整个高度和宽度,请不要使用绝对定位.而是在按钮上指定100%的高度和宽度,并在包装​​器上使用填充来偏移按钮:

.wrapper {
    height: 300px;
    width: 300px;
    background-color: #f33;
    padding: 3px;
    Box-sizing: border-Box;
}

.wrapper button {
    height: 100%;
    width: 100%;
}
<div class="wrapper">
    <button>Hello world</button>
</div>

(如果不能使用Box-sizing,请从包装器的尺寸中减去填充.)

文本的垂直对齐可能与浏览器认情况下绘制按钮控件的方式有关,通常基于系统按钮控件.

原文地址:https://www.jb51.cc/html/226417.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐