[英]Button with absolute position doesn't stretch to full width
Button element doesn't stretch to full parent width with left/right zero technique. 使用左/右零技术,Button元素不会拉伸到完整的父宽度。 It perfectly works for
a
tag but not for button
. 它完美地适用于
a
标签而不是button
。 What am I missing? 我错过了什么?
The question is why left/right approach isn't working for button. 问题是为什么左/右方法不适用于按钮。 I know that I can use wrapper,
calc()
or flexbox. 我知道我可以使用wrapper,
calc()
或flexbox。 But it seems strange that old way doesn't work. 但旧的方式不起作用似乎很奇怪。
#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>
You can set width:inherit
on the button
, but be aware that it won't work when box-sizing:border-box
is set on the container, otherwise you will probably need width:calc(100% - paddings)
, also mentioned in the other answer. 你可以在
button
上设置width:inherit
,但要注意当box-sizing:border-box
时它不起作用box-sizing:border-box
在容器上设置box-sizing:border-box
,否则你可能需要width:calc(100% - paddings)
,也提到在另一个答案。
button {
width: inherit;
}
you can add button width to 100% so that it will be 100% of its parent container. 您可以将按钮宽度添加到100%,以便它将是其父容器的100%。
.button {
position: absolute;
left: 0;
right: 0;
**width: 100%;**
background: green;
color: white;
border: 1px solid #000;
}
Add width: calc();
添加
width: calc();
to the .button
as in 到
.button
如
a.button {
top: 0;
width: calc();
}
This will stretch it to 100% and retain your padding of the parent element. 这会将其拉伸到100%并保留父元素的填充。
Your button is overflowing the parent since your button is absolute
and has left of 20px
. 由于您的按钮是
absolute
并且剩下20px
,因此您的按钮溢出了父按钮。
There is no need to compensate for the parent padding. 无需补偿父填充。
Change left left: 0px;
left: 0px;
改left: 0px;
or remove position: absolute;
或删除
position: absolute;
. 。
.button{
position: absolute;
left: 0px;
...
}
I would rather be removing position: absolute
; 我宁愿删除
position: absolute
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.