2017-08-03 56 views
1

我是後端開發人員,他目前必須爲小任務做前端工作。我的問題是這樣的圖像CSS使標籤文本與選定文本對齊

enter image description here

背景只是爲了調試的目的。然而,這條紅線表明標籤中的文字(左)與右邊的文字不一致。我使用的反應,在此可以同時創建

<div className='select'> 
    <label className='selectLabel'>{this.props.label}</label> 
    <select id ='select' onChange={this.props.onChange}> 
    {this.props.options} 
    </select> 
</div> 

這裏我的組件是我的CSS,只要我不知道我在做什麼我就做隨機的東西和任何工作

.select{ 
    width:100%; 
    padding-left: 2%; 
    text-align: left; 
    margin: 10px auto 10px; 
    position: relative; 
} 
#select{ 
    border: 1px solid #ccc; 
    font-size: 16px; 
    height: 34px; 
    width: 268px; 
    background-color: aqua; 
} 
.selectLabel{ 
    clear: both; 
    float:left; 
    display:block; 
    height: 34px; 
    vertical-align: middle; 
    width: 268px; 
    line-height:25px; 
    background-color: aquamarine; 
} 

什麼我應該添加還是更改以使兩個文本彼此對齊?

+0

的問題是不相關的陣營所有,而是HTML和CSS。爲了便於調試,請考慮提取並保存生成的HTML。您可以使用瀏覽器的開發人員工具獲取它。我的第一個猜測是浮動。 –

+0

將'line-height:34px'設置爲'.selectLabel'。 – Terry

+0

'.selectLabel {display:inline-block}'應該就夠了,你也不需要'float' – Morpheus

回答

1

添加display: flex; align-items: center;.selectLabel就能解決問題

.select{ 
 
    width:100%; 
 
    padding-left: 2%; 
 
    text-align: left; 
 
    margin: 10px auto 10px; 
 
    position: relative; 
 
} 
 
#select{ 
 
    border: 1px solid #ccc; 
 
    font-size: 16px; 
 
    height: 34px; 
 
    width: 268px; 
 
    background-color: aqua; 
 
} 
 
.selectLabel{ 
 
    clear: both; 
 
    float:left; 
 
    display:flex; 
 
    align-items: center; 
 
    height: 34px; 
 
    vertical-align: middle; 
 
    width: 268px; 
 
    line-height:25px; 
 
    background-color: aquamarine; 
 
}
<div class='select'> 
 
    <label class='selectLabel'>{this.props.label}</label> 
 
    <select id ='select'> 
 
    <option value="1">1</option> 
 
     <option value="2">2</option> 
 
    </select> 
 
</div>

+0

沒有前綴的全局瀏覽器支持:86.91%(http://caniuse.com/#search=flex) –

+0

與其他解決方案相比,這種解決方案引入了大量的佈局複雜性,並且會在以後出現反彈。 –

1

無需浮動標籤或定義它的高度。使用內聯塊作爲它的顯示模式。對於工作示例

.selectLabel{ 
    display:inline-block; 
    background-color: aquamarine; 
} 

見代碼筆:https://codepen.io/anon/pen/qXaoGb

1

使用line-height而不是vertical-align: middle;

inline-block代替display:block; float:left;

爲您的標籤。

https://jsfiddle.net/r8bzo8c1/1/

.select{ 
 
    width:100%; 
 
    padding-left: 2%; 
 
    text-align: left; 
 
    margin: 10px auto 10px; 
 
    position: relative; 
 
} 
 
#select{ 
 
    border: 1px solid #ccc; 
 
    font-size: 16px; 
 
    height: 34px; 
 
    width: 150px; 
 
    background-color: aqua; 
 
} 
 
.selectLabel{ 
 
    display:inline-block; 
 
    height: 34px; 
 
    width: 150px; 
 
    line-height:34px; 
 
    background-color: aquamarine; 
 
}
<div className='select'> 
 
    <label class='selectLabel'>Label</label><select id ='select'> 
 
    <option>A</option> 
 
    <option>B</option> 
 
    </select> 
 
</div>