2017-03-08 52 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中的图像 –