根据我的计算,两边的边距应该使两个标签完全位于div的中心
你的计算不完全正确,你所做的是200+9+10+50+9
,也就是278
,这似乎适合宽度为278
的元素.但你没有包括的是新行(Why does the browser renders a newline as space?)引入的两个input
元素之间的空间.
如果删除该新行,它将起作用:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
input {
outline: none;
}
.search-box {
height: 50px;
width: 280px;
border: 1px solid #DCDCDC;
background-color: #F5F5F5;
margin: 10px auto;
border-radius: 10px;
box-shadow: 2px 2px 1px #D3D3D3, -2px 2px 1px #D3D3D3;
}
#input-search {
width: 200px;
height: 30px;
border: 1px solid #DCDCDC;
margin: 9px 10px 9px 9px;
border-radius: 5px;
text-indent: 3px;
}
#btn {
height: 30px;
width: 50px;
font-size: 12px;
font-weight: 600;
color: #fff;
border-radius: 5px;
border: 1px solid #008080;
display: inline-block;
margin: 9px 9px 9px 0;
background-image: linear-gradient(#20B2AA, #5F9EA0);
}
<div class="search-box">
<input type="text" id="input-search" placeholder="search"><!--
--><input type="button" value="GO" id="btn">
</div>
但为了避免此类问题,您可能希望使用display: flex
,而不是手动计算元素的正确宽度.
- 将
.search-box
中的display
设置为flex
.
- 拆除
input
个元件中的width
和height
,flex将处理该问题.
- 设置所需的
padding
,而不是将width
设置为#btn
.
- 在
#input-search
上使用flex: 1 1 auto;
使其拉伸,并使用可用的尺寸.
这样,您就可以更改.search-box
中的width
,而无需更改输入元素的宽度,还可以更新按钮和文本的字体大小.通过将with
更改为max-width
,您甚至可以使.search-box
响应.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
input {
outline: none;
}
.search-box {
height: 50px;
width: 280px;
border: 1px solid #DCDCDC;
background-color: #F5F5F5;
margin: 10px auto;
border-radius: 10px;
box-shadow: 2px 2px 1px #D3D3D3, -2px 2px 1px #D3D3D3;
display: flex;
}
#input-search {
border: 1px solid #DCDCDC;
margin: 9px 10px 9px 9px;
border-radius: 5px;
text-indent: 3px;
flex: 1 1 auto;
}
#btn {
font-size: 12px;
font-weight: 600;
color: #fff;
border-radius: 5px;
border: 1px solid #008080;
display: inline-block;
margin: 9px 9px 9px 0;
padding-left: 15px;
padding-right: 15px;
background-image: linear-gradient(#20B2AA, #5F9EA0);
}
<div class="search-box">
<input type="text" id="input-search" placeholder="search">
<input type="button" value="GO" id="btn">
</div>
为了进一步改进CSS,我将从input
个元素中删除margin
,并在.search-box
和gap
上将其更改为padding
.而不是px
单位padding
单位#btn
我会用em
.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
input {
outline: none;
}
.search-box {
height: 50px;
width: 280px;
border: 1px solid #DCDCDC;
background-color: #F5F5F5;
margin: 10px auto;
border-radius: 10px;
box-shadow: 2px 2px 1px #D3D3D3, -2px 2px 1px #D3D3D3;
display: flex;
padding: 9px;
gap: 10px;
}
#input-search {
border: 1px solid #DCDCDC;
border-radius: 5px;
text-indent: 3px;
flex: 1 1 auto;
}
#btn {
font-size: 12px;
font-weight: 600;
color: #fff;
border-radius: 5px;
border: 1px solid #008080;
display: inline-block;
padding-left: 1.2em;
padding-right: 1.2em;
background-image: linear-gradient(#20B2AA, #5F9EA0);
}
<div class="search-box">
<input type="text" id="input-search" placeholder="search">
<input type="button" value="GO" id="btn">
</div>