我有5个按钮。我希望它们占用父div的可用宽度,每个div的大小相同:
<div style="width: 100%; background-color: red;">
<button type="button" style="width: 20%;">A</button>
<button type="button" style="width: 20%;">B</button>
<button type="button" style="width: 20%;">C</button>
<button type="button" style="width: 20%;">D</button>
<button type="button" style="width: 20%;">E</button>
</div>
有没有办法可以做到这一点,而无需手动弄清楚它们每个都需要20%的宽度?我想在运行时删除一个按钮,这意味着我必须再次将每个剩余的按钮更新为width = 25%。
只是检查是否有更自动化的方法。
由于
答案 0 :(得分:13)
最简单的方法和最强大的方法是使用表格:
<style>
.buttons {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
background-color: red;
}
.buttons button {
width: 100%;
}
</style>
<table class=buttons>
<tr>
<td><button type="button">A</button>
<td><button type="button">B</button>
<td><button type="button">C</button>
<td><button type="button">D</button>
<td><button type="button">E</button>
</table>
(如果他们看到你的代码,这几天不会提高你的同事的声誉,虽然它实际上可能比任何替代方案更好地解决问题。所以你可能会考虑做下一个最好的事情:使用div
标记和display: table
等。在不支持此类CSS功能的旧浏览器上失败。)
答案 1 :(得分:6)
我知道这是旧的,但万一其他人仍然在寻找不同的方法,这是我最喜欢的方法:Flexbox!
<div style="width: 100%; background-color: red;">
<button type="button">A</button>
<button type="button">B</button>
<button type="button">C</button>
<button type="button">D</button>
<button type="button">E</button>
</div>
div {
display:flex;
justify-content:space-around;
}
button {
width: 100%;
margin: 5px; /* or whatever you like */
}
无论您拥有多少个按钮,它都会自动调整按钮宽度并填充div
。
答案 2 :(得分:3)
这就是我如何处理这样的情况,从前端网格系统中排队。使用课程!删除按钮后,更改课程。 Here's a fiddle
您的HTML标记可能会更改为:
<div>
<button type="button" class="fiveup">A</button>
<button type="button" class="fiveup">B</button>
<button type="button" class="fiveup">C</button>
<button type="button" class="fiveup">D</button>
<button type="button" class="fiveup" id="remove_this">E</button>
</div>
<button id="remove_one">Remove One</button>
像这样的CSS:
.fiveup {width: 18%;margin:1%;float: left;}
.fourup {width: 23%;margin:1%;float: left;}
和jQuery这样,虽然你可能想要使用这个脚本作为任何进程删除按钮的一部分:
$('#remove_one').click(function(){
$('#remove_this').remove();
$('button').each(function(){
$(this).removeClass('fiveup').addClass('fourup');
});
});
答案 3 :(得分:0)
如果我们认为他们的父母大小相同,那么你有两个解决问题的方法:
CSS:
button { /* You may want to limit the selector */
width: 100%; /* Or any other percent */
}
JavaScript(jQuery):
$("button").width("100%");
但请注意,为了确保您也获得准确的值,您可能希望坚持使用像素。如果您愿意使用JavaScript,也可以使用计算宽度。
修改强>
如果您想在没有jQuery的情况下使用JavaScript,请尝试:
var buttons = document.getElementsByTagName("button"),
i = 0;
for (; i < buttons.length; i++) {
buttons[i].width = "100%"; //Or any other value
}
但请注意,如果您想要更复杂的查询,则必须替换.getElementsByTagName()
。
答案 4 :(得分:0)
我认为,使用jQuery,你可以做一些更有活力的事情。
算法的过程如下:
获取div的宽度,放入变量。
将宽度除以按钮数,并将该答案放入变量中。
运行一个函数,无论多少次都需要创建一个宽度的按钮。