2017-09-22 31 views
2

我想讓標題在居中的div元素的左上角對齊。我能想到的唯一方法就是設置positionrelative並使用top的值爲20%。問題在於它導致頁眉將頁面向右拉伸,如fiddle中所見。如何正確地將標題與居中的div元素對齊?

body { 
 
    font-family: Europa; 
 
} 
 

 
.header { 
 
    position: relative; 
 
    left: 20%; 
 
    display: block; 
 
    margin-left: auto; 
 
    margin-right: auto 
 
} 
 

 
h4 { 
 
    font-size: 5em; 
 
    margin: 0 auto; 
 
} 
 

 
.box { 
 
    height: 500px; 
 
    width: 500px; 
 
    position: relative; 
 
    border-radius: 20px; 
 
    background: #6441a5; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    right: 0; 
 
    margin: auto; 
 
}
<div class="header"> 
 
    <h4>header</h4> 
 
</div> 
 

 
<div class="box"> 
 
</div>

回答

0

使用.centered包裝DIV您可以更輕鬆地獲得您想要的結果W /保持流體元素如果想要的。

<div class="centered"> 
    <h4>header</h4> 
    <div class="speech-bubble"></div> 
</div> 

<style> 
h4 { 
    font-size: 5em; 
    margin: 0 auto; 
} 

.speech-bubble { 
    height: 500px; 
    width: 100%; 
    border-radius: 20px; 
    background:#6441a5; 
    margin: auto; 
} 
.centered{ 
    width:500px; 
    margin: 0 auto; 
    position: relative; 
} 

</style> 
1

只需給你的報頭塊相同的寬度的框。

body { 
 
    font-family: Europa; 
 
} 
 

 
.header { 
 
    position: relative; 
 
    width:500px; 
 
    display: block; 
 
    margin-left: auto; 
 
    margin-right: auto 
 
} 
 

 
h4 { 
 
    font-size: 5em; 
 
    margin: 0 auto; 
 
} 
 

 
.box { 
 
    height: 500px; 
 
    width: 500px; 
 
    position: relative; 
 
    border-radius: 20px; 
 
    background: #6441a5; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    right: 0; 
 
    margin: auto; 
 
}
<div class="header"> 
 
    <h4>header</h4> 
 
</div> 
 

 
<div class="box"> 
 
</div>

0

最簡單的辦法是把你的兩個元素在一個DIV,像這樣:

body { 
 
    font-family: Europa; 
 
} 
 

 
.header { 
 
    display: block; 
 
    margin: auto; 
 
    width: 500px; 
 
} 
 

 
h4 { 
 
    font-size: 5em; 
 
    margin: 0 auto; 
 
} 
 

 
.speech-bubble { 
 
    height: 500px; 
 
    width:500px; 
 
    position: relative; 
 
    border-radius: 20px; 
 
    background:#6441a5; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    right: 0; 
 
}
<div class="header"> 
 
     <h4>header</h4> 
 

 
     <div class="speech-bubble"> 
 

 
     </div> 
 
    </div>