2017-03-03 64 views
0

美好的一天,我與使用CSS創建HTML元素看起來的具體結構麻煩如下:如何將零線高度的div文本元素居中?

enter image description here

我tryings與此結束建議:

enter image description here

我試着以編程的方式來做,但總是當我將數字和字符串之間的行高CSS屬性設置爲空時,div的整個內容自然會被推得更高,而且我不能直接將它中間。即使使用像素推動,它也可能很痛苦而且不準確。

<!DOCTYPE html><head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
</head> 


<style> 
.circle 
    { 
    width: 100px; 
    height: 100px; 
    background: red; 
    -moz-border-radius: 50px; 
    -webkit-border-radius: 50px; 
    border-radius: 50px; 
    } 
</style> 

<body> 

<div style="margin-left:100px;"> 
<div align="center" class="circle"> 
<h1>9</h1> 
<p>LEVEL</p> 
</div> 
</div> 

</body> 

</html> 

我試圖使用任何邊距或高度屬性,但沒有積極的結果。這是我的問題,現在怎麼看:

enter image description here

你有任何想法如何編程修復它? (任何其它類似的問題didn't幫我,感謝您的時間)

回答

1

標記:

<div class="level-container"> 
    <span class="number">9</span> 
    <span class="level">level</span> 
</div> 

SCSS:

.level-container { 
    background-color: gray; 
    width: 300px; 
    height: 300px; 
    border-radius: 50%; 
    display: flex; 
    flex-direction: column; 
    justify-content: center; 

    .number, 
    .level { 
    align-self: center; 
    justify-self: center; 
    line-height: 0; 
    margin: 20px; 
    } 

    .number { 
    font-size: 60px; 
    } 

    .level { 
    font-size: 30px; 
    } 
} 

邁克爾的解決方案類似,但我的演示,使容器內的內容有line-height: 0;

Demo

+0

感謝您的回答與線高度:0 ......這對我有用,我會記住你的解決方案,再次感謝 –

2

您可以使用line-height: 1讓每一個元素的行高匹配它的字體大小,請從h1p默認邊距,然後用Flexbox的垂直和水平居中圓內容。

align屬性已被棄用btw。你應該使用CSS中心而不是HTML。

* {margin:0;} 
 
.circle { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: red; 
 
    -moz-border-radius: 50px; 
 
    -webkit-border-radius: 50px; 
 
    border-radius: 50px; 
 
    line-height: 1; 
 
    display: flex; 
 
    flex-direction: column; 
 
    justify-content: center; 
 
    align-items: center; 
 
}
<div style="margin-left:100px;"> 
 
    <div class="circle"> 
 
    <h1>9</h1> 
 
    <p>LEVEL</p> 
 
    </div> 
 
</div>

+0

哈哈哈:d ..我永遠不會讓這對我自己這樣的..好的,謝謝你..這就是正確的答案對我來說 –