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,请从包装器的尺寸中减去填充.)

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

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些