输入和按钮宽度只占用100%,但不会出现在彼此旁边
问题描述:
我有一个黄色的div,低于输入背景红色和背景灰色的背景。我希望输入和按钮彼此相邻,但不起作用。但它很奇怪,因为我有80%的输入和20%的按钮,都没有边距,所以它的奇怪,不工作。你知道问题在哪里吗?输入和按钮宽度只占用100%,但不会出现在彼此旁边
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
outline: 0;
}
input,
select,
textarea,
button {
padding: 15px;
width: 100%;
}
select,
input,
button {
border: 0;
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
cursor: pointer;
}
img {
width: 100%;
max-width: 100%;
vertical-align: middle;
margin: 0;
}
a img {
border: none;
margin: 0;
}
a {
text-decoration: none;
}
ul {
list-style: none;
}
/*CONTAINER*/
.container {
float: left;
width: 100%;
}
.content {
width: 64%;
margin: 0 auto;
padding: 30px 0;
}
.box {
width: auto;
float: left;
}
.box-search {
width: 23.3%;
margin: 0;
}
.box-small {
width: 22.75%;
margin-right: 3%;
margin-top: 3%;
}
.filter-city {
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
.filter-city input {
width: 80%;
border: 0 !important;
background-color: red;
margin-right: 0 !important;
padding-right: 0;
}
.filter-city button {
width: 20%;
margin-left: 0 !important;
color: $color-white;
background-color: $color-primary;
margin-right: 0 !important;
}
<section class="container">
<div class="content">
<div class="box box-small filter_results">
<div style="width:100%; background-color:yellow; height:40px;">
</div>
<div class="filter-city">
<input class="m_top" value="Test" type="text">
<button><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</div>
<div class="results"></div>
</div>
</section>
答
看来这个问题是导致两件事情:
-
输入和按键之间的空白。
内联和内嵌块元素允许其他元素在包含空格的行的旁边存在。这两个元素之间的换行符在它们之间引入了一个空间,这不是由您的百分比计算的。
-
水平按钮填充大于其计算的宽度。
该按钮有
padding:15px
,它设置水平和垂直填充。但是示例中的按钮宽度小于15px,因此即使使用box-sizing:border-box
,按钮的宽度也会比您的百分比大。
这里有一个工作示例:
.container {
float: left;
width: 100%;
}
.content {
width: 64%;
margin: 0 auto;
padding: 30px 0;
}
.box {
float: left;
}
.box-search {
width: 23.3%;
}
.box-small {
width: 22.75%;
margin-right: 3%;
margin-top: 3%;
}
.filter-city input,
.filter-city button {
padding: 15px 0;
margin: 0;
border: 0;
}
.filter-city input {
width: 80%;
background-color: red;
}
.filter-city button {
width: 20%;
background-color: lightgray;
}
<section class="container">
<div class="content">
<div class="box box-small filter_results">
<div style="width:100%; background-color:yellow; height:40px;"></div>
<div class="filter-city">
<input class="m_top" value="Test" type="text"><button>Test</button>
</div>
</div>
<div class="results"></div>
</div>
</section>
答
如果你只需要添加
filter-city {
display: flex;
....
}
它应该工作。
https://jsfiddle.net/g97qf57o/
说实话,我不完全知道为什么这工作,但我的经验Flexbox,就可以解决大部分布局问题。
答
您是否检查过Firebug或Chrome Developer工具中的“display”? IIRC,输入默认为块级元素,因此应用“display:inline-block;”属性到必要的投入应该解决问题。
答
你应该使用float : left
需要彼此相邻的div和包含div。