[英]Button with absolute position doesn't stretch to full width
使用左/右零技术,Button元素不会拉伸到完整的父宽度。 它完美地适用于a
标签而不是button
。 我错过了什么?
问题是为什么左/右方法不适用于按钮。 我知道我可以使用wrapper, calc()
或flexbox。 但旧的方式不起作用似乎很奇怪。
#container { position: relative; width: 400px; height: 60px; padding: 0 20px; background: #ccc; } .button { position: absolute; left: 20px; right: 20px; height: 20px; background: green; color: white; border: 1px solid #000; } a.button { top: 0; } button.button { top: 20px; display: block; } button.button-full { width: 100%; top: 40px; }
<div id="container"> <a class="button">Link button</a> <button class="button">Button button</button> <button class="button button-full">Button button</button> </div>
你可以在button
上设置width:inherit
,但要注意当box-sizing:border-box
时它不起作用box-sizing:border-box
在容器上设置box-sizing:border-box
,否则你可能需要width:calc(100% - paddings)
,也提到在另一个答案。
button {
width: inherit;
}
您可以将按钮宽度添加到100%,以便它将是其父容器的100%。
.button {
position: absolute;
left: 0;
right: 0;
**width: 100%;**
background: green;
color: white;
border: 1px solid #000;
}
添加width: calc();
到.button
如
a.button {
top: 0;
width: calc();
}
这会将其拉伸到100%并保留父元素的填充。
由于您的按钮是absolute
并且剩下20px
,因此您的按钮溢出了父按钮。
无需补偿父填充。
left: 0px;
改left: 0px;
或删除position: absolute;
。
.button{
position: absolute;
left: 0px;
...
}
我宁愿删除position: absolute
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.