I was experimenting with div and trying to create a composite control using
- Label
- Text field
HTML
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-control {
background-color: yellow;
margin: 0;
padding: 0;
}
.form-control[data-layoutOrder=horizontal] div[data-section=title] {
display: inline-block;
background-color: red;
width: 50%;
margin: 0;
padding: 0;
}
.form-control div[data-section=data] {
background-color: green;
display: inline-block;
width: 50%;
margin: 0;
padding: 0;
}
<div class="form-control" data-layoutOrder="horizontal">
<div data-section="title">
<label for="firstName">First Name</label>
</div>
<div data-section="data">
<input type="text" placeholder="First Name" id="firstName">
</div>
</div>
The output of the above code was expected to be label and input to be adjacent to each other, but thats not the case. The div wrapping text field is actually floating to next line, though I have set width of label div and textfield div to 50% using CSS.
I tried setting padding, margin etc to 0, but none of them worked. What is causing textfield div to float to the next line. When I changed one of the div's width to 49%, both divs got aligned on single line. I didn't understand as why it is behaving so?
Note: I could able to get both of them adjacent to each other using float property - float:left
for label div & float:right
property for textfield div. But I want to know as why setting 50% width didn't work without float. Do I really need to use float or am I missing something.
EDIT 1:
I found another solution by using white-space
attribute as
.form-control {
background-color: yellow;
margin:0;
padding:0;
white-space:nowrap;
}
.form-control div[data-section=data] {
background-color : green;
display: inline-block;
width: 50%;
margin:0;
padding:0;
white-space:normal;
}
EDIT 2: Using flex
style also has desired effect.
While searching more, I also came across achieving the same effect using flex
style. Note that, it isn't supported in IE 10 and below. Refer caniuse.
.form-control {
background-color: yellow;
margin: 0;
padding: 0;
display: flex;
display: -webkit-flex;
}
.form-control[data-layoutOrder=horizontal] div[data-section=title] {
display: inline-block;
background-color: red;
width: 50%;
margin: 0;
padding: 0;
flex:1;
}
.form-control div[data-section=data] {
background-color: green;
display: inline-block;
width: 50%;
margin: 0;
padding: 0;
flex:1;
}