使用`box-sizing:border-box`和`inline-block`元素 [英] Using `box-sizing: border-box` with `inline-block` elements
问题描述
我想使用 box-sizing:border-box
CSS属性将表单分为左右一半:
I'd like to use the box-sizing: border-box
CSS property to split a form into a left and right half:
<form class=container>
<fieldset class=left>
<label>Description</label>
<textarea name=description></textarea>
</fieldset>
<fieldset class=right>
<label>Name</label>
<input type=text name=name />
</fieldset>
</form>
为了完成这项工作,我需要同时浮动两个< fieldset> ;
左侧的元素:
In order to make this work, I need to float both <fieldset>
elements to the left:
.left, .right {
width: 50%;
margin-left: 0px;
marign-right: 0px;
box-sizing: border-box;
float: left;
}
当然,问题在于,由于< fieldset>
是浮动的,它们不再流入,并且< form>
元素的高度为0(除非i添加一个clearfix之类的东西)。如果我删除了float属性,并将其显示更改为 inline-block
,则它们又恢复了流动,但它们不再彼此相邻排列。
The problem is of course that since the <fieldset>
's are floated, they are no longer in-flow, and the <form>
element gets a height of 0 (unless i add a clearfix or something). If I remove the float property and change their display to inline-block
, they're back in flow, but they no longer line-up next to eachother.
是否可以在此处使用边框,而无需添加clearfix元素(或
:在
伪元素之后)?
Is there some way to use border-box
here without needing to add a clearfix element (or :after
pseudo element)?
For reference, here's a fiddle that uses floats, and here's a fiddle that uses inline-block.
推荐答案
这是一个很常见的问题。
That's quite a common problem.
在容器上添加溢出
值,尽管浏览器没有浮动元素,浏览器仍将重新计算其尺寸。
Adding an overflow
value on the container, will have the browser to recalculate the container's dimensions despite it have no not-floated elements.
.container { overflow: hidden; }
Before and After
这篇关于使用`box-sizing:border-box`和`inline-block`元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!