中心h1在img元素中垂直和水平

时间:2016-12-01 13:10:06

标签: html css

当图片宽度为100%且始终保持宽高比时,如何将h1置于img元素中心? This pen shows what I mean。我在SO上看到了一些答案,但图像的宽度和高度始终固定。

5 个答案:

答案 0 :(得分:2)

为了实现你的目标,你需要将img和h1都放入div并使用定位来使h1居中

#headerImage {
    width:100%;        
    margin-left:auto;
    margin-right:auto;
    background-position:center;
    background-repeat:no-repeat;
   }

#greeting{
  
  padding: 0px;
  position: relative;

}

#greetin-h1{
text-align: center;
color:#000;
  position: absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  z-index: 9999;
  
}
<div id="greeting">
    <img id="headerImage" src="http://study.com/cimages/course-image/intro-to-business-syllabus-resource-lesson-plans_138757_large.jpg" alt=""/>
    <h1 id="greetin-h1">THIS IS H1 ELEMENT</h1>
</div>

答案 1 :(得分:2)

为什么不将图像用作背景?

html, body{
  width: 100vw;
}
#greeting{
padding: 140px 20px 50px 20px;
background-image: url("http://study.com/cimages/course-image/intro-to-business-syllabus-resource-lesson-plans_138757_large.jpg");
  background-repeat: no-repeat;
    background-size: cover;
}

#greetin-h1{
  text-align: center;
  color:black;
}
	<div id="greeting">
		<h1 id="greetin-h1">THIS IS H1 ELEMENT</h1>
	</div>

答案 2 :(得分:1)

问候语添加css样式

#greetin {
            padding: 140px 20px 50px 20px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }

答案 3 :(得分:1)

.wrapper {
  position: relative;
}

img {
  display: block;
  width: 100%;
}

h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: gold;
}
<div class="wrapper">
  <img src="https://www.propointgraphics.com/wp-content/uploads/2016/01/stock-photos-vince_3219813k.jpg" alt="">
  <h1>Hello, World!</h1>
</div>

答案 4 :(得分:1)

使用相对和绝对定位,表格和表格单元格显示的组合,如下所示:

<强> CSS:

#headerImage {
    position: relative;
    text-align: center;
    display: inline-block;
}
#headerImage img {
    max-width: 100%;
}
#greeting {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
#greetin-h1 {
    margin: 0;
    display: table;
    width: 100%;
    height: 100%;
}
#greetin-h1 span {
    display: table-cell;
    vertical-align: middle;
}

<强> HTML:

<div id="headerImage">
   <div id="greeting">
      <h1 id="greetin-h1"><span>THIS IS H1 ELEMENT</span></h1>
   </div>
   <img src="http://study.com/cimages/course-image/intro-to-business-syllabus-resource-lesson-plans_138757_large.jpg" alt="">
</div>

小提琴:https://jsfiddle.net/ve8sot21/1

这样,无论图像尺寸如何,h1始终水平和垂直居中。

相关问题