2017-04-24 63 views
1

我無法使按鈕高度與不同的字體大小相同。我必須使用em來設置響應式設計的高度和寬度。如何使按鈕高度與不同的字體大小相同

這裏是例子jsfiddle

CSS:

body{ 
    font-size:16px; 
} 
.btn{ 
    height:4em; 
    font-size:1em; 
} 
.btn2{ 
    height:4em; 
    font-size:1.50em; 
} 

HTML:

<button class="btn">First Button is 64px as expected</button> 
<br><br> 
<button class="btn2">Why this is not same height with first one?</button> 

<p> 
    How to make same height buttons with differnet font sizes ? 
</p> 
+0

試圖給他們兩個相同的寬度 –

+0

是的。當你給相同的寬度,它按預期工作。但爲什麼 ?這是一個錯誤?這裏更新並且正在工作。兩者都具有相同的寬度和預期工作。 https://jsfiddle.net/ynxqjytz/4/ –

+0

那是因爲你正在使用EM取決於字體大小。 –

回答

2

的原因,這兩個<button>元素大小不同是因爲你在來定義的height的相對em單位的大小,這是從當前的font-size確定的,並且兩個<button>元素都有不同的font-size

雖然你說你「必須使用em爲&hellip;響應大小就可以了,而應使用rem單元,這是文件的」根他們的人,一個rem將永遠是相同的大小,而不管的任何後代元件的改變font-size

,例如:

let button1 = document.querySelector('button.btn'), 
 
    button2 = document.querySelector('button.btn2'); 
 

 
console.log(button1.clientHeight, button2.clientHeight); 
 
// 60 60 (in my browser, yours will vary, but both 
 
// buttons should show the same size).
body { 
 
    font-size: 16px; 
 
    box-sizing: border-box; 
 
} 
 

 
.btn { 
 
    height: 4rem; 
 
    line-height: 4rem; 
 
    font-size: 1em; 
 
} 
 

 
.btn2 { 
 
    height: 4rem; 
 
    line-height: 4rem; 
 
    font-size: 1.50em; 
 
}
<button class="btn">First Button is 32px as expected</button> 
 
<br /> 
 
<br /> 
 
<button class="btn2">Why this is not same height with first one?</button> 
 

 
<p> 
 
    How to make same height buttons with differnet font sizes ? 
 
</p>

+0

的'線height'是不必要 – LGSon

1

em s的綁字體大小,所以當你改變btn2字體大小你改變什麼height: 4em評估。如果你能使用它們rem旨意解決這個問題,你

body{ 
 
    font-size:16px; 
 
} 
 
.btn{ 
 
    height: 4rem; 
 
    font-size:1em; 
 
} 
 
.btn2{ 
 
    font-size:1.50em; 
 
    height: 4rem; 
 
}
<button class="btn">First Button is 64px as expected</button> 
 
<br><br> 
 
<button class="btn2">Why this is not same height with first one?</button> 
 

 
<p> 
 
    How to make same height buttons with differnet font sizes ? 
 
</p>

+0

謝謝你的回答。但我不明白你爲什麼說「如果你能使用它們?我不是一個官方的前端開發者。 –

+0

@OğuzCanSertel他說,因爲'rem'不能在較早版本的IE支持 – LGSon

+0

@OğuzCanSertel這是正確的檢查[caniuse:REMS](http://caniuse.com/#feat=rem) – chazsolo

1

您正在爲字體設置ems,併爲高度設置ems。 'em'等同於當前的字體大小。它的初始CSS設置爲16px,因此1em = 16px,其中* 4的高度爲btn爲64px。當您在btn2中更改字體大小時,您將整體調整該對象的em值,所以4 em的高度現在爲1.5 * 16px * 4 = 96px。

除非您能夠將按鈕的em值與字體大小em分開設置,否則我不認爲如果不手動將4em縮小到更小的值,那麼數學就會在btn2上運行。如果你想保持一致的4em,那麼我會建議嵌套元素,所以你可以在不同的元素上設置值。

相關問題