2017-03-08 48 views
0

我想把標題放在圖像的中心我試着放圖像然後標題然後給標題負邊距,但是當我這樣做時,其他元素上去,使它看起來很糟糕如何把標題放在圖像的中心

<div> 
 
    <img src="https://res.cloudinary.com/dte7bat2g/image/upload/v1488492447/sample.jpg" alt="rose image " 
 
    <h2>i want to put this heading in the center of the above image </h2> 
 
</div>

+0

設置圖片爲背景' - image' – Swellar

+0

使用的位置是:絕對 –

回答

0

喜歡這個?

div { 
 
    background-image: url("https://res.cloudinary.com/dte7bat2g/image/upload/v1488492447/sample.jpg"); 
 
    height: 300px; 
 
    position: relative; 
 
} 
 

 
h2 { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%) 
 
}
<div> 
 
    <h2>i want to put this heading in the center of the above image </h2> 
 
</div>

+1

@Downvoter你能評論的向下投票的原因嗎? – Swellar

+0

不,我想它作爲一個圖像裏面的div而不是在css –

0

嘗試是這樣的

.image { 
 
    position: relative; 
 
    float: left; 
 
} 
 
.image h2 { 
 
    position: absolute; 
 
    z-index: 2; 
 
    top: 50%; 
 
    left: 0; 
 
    right: 0; 
 
    margin: 0 auto; 
 
}
<div class="image"> 
 
    <img src="https://res.cloudinary.com/dte7bat2g/image/upload/v1488492447/sample.jpg" alt="rose image " /> 
 
    <h2>i want to put this heading in the center of the above image </h2> 
 
</div>

0

使用position: absolute上的div<h2>position: relative

.parent { 
 
    position: relative; 
 
} 
 

 
.child { 
 
    position: absolute; 
 
    left: 0; 
 
    right: 0; 
 
    top: 0; 
 
    bottom: 0; 
 
    text-align: center; 
 
    margin: auto; 
 
    height: 20px; 
 
}
<div class="parent"> 
 
    <img src="https://res.cloudinary.com/dte7bat2g/image/upload/v1488492447/sample.jpg" alt="rose image" /> 
 
    <h2 class="child">i want to put this heading in the center of the above image </h2> 
 
</div>

+0

它不起作用在我的設計中我有一個標題 當我申請你的代碼時,標題上升到標題 ,我也希望它的div在中心現在我不能把它放在中心 –

+0

在特定的類而不是通用的'div'和'h2'上應用css,否則其他div可能繼承這裏的所有屬性。 – nashcheez

-1

喜歡這個?

h2{ 
 
    \t \t padding:20%; 
 
\t }
<body background="http://wallpapercave.com/wp/N3BgXEI.jpg"> 
 
<div> 
 
    <h2>I want to put this heading in the center of the above image </h2> 
 
</div> 
 
</body>

0

另一種方法是使用flexbackground-image

.bg { 
 
    width: 200px; 
 
    height: 200px; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    background-image: url("http://placehold.it/200x200"); 
 
    background-repeat: no-repeat; 
 

 
}
<div class="bg"> 
 
    <h1> TEXT </h1> 
 
</div>

+0

我希望它在html中的圖像 –