垂直对齐H2跨度到DIV的中心

时间:2015-12-05 10:39:00

标签: jquery html css twitter-bootstrap

我正试图在DIV的中间垂直对齐一个说“我的标题”的h2跨度。

我尝试使用vertical - align,但该属性并未改变照片的位置。

我正在使用bootstrap,问题是随着页面窗口变小,文本因相对定位而消失,此时相对定位只能起作用。

.imageInside { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 {
   line-height:100px; 
   vertical-align:middle; 
   position: absolute; 
   top: 0; 
   left: 10; 
   width: 100%; 
}

h2 {
	z-index:1;
}

h2 span { 
   color: white; 
   font: bold 0.8em 'montserratsemi_bold', Helvetica, Sans-Serif; 
   letter-spacing: -1px;  
   background: rgb(0, 0, 0); /* fallback color */
   background: rgba(0, 0, 0, 0.7);
   padding: 10px; 
}
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>
	<head>
		<title>Tutorial</title>
		<!-- Tab Title -->
		<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
		<!-- 960 Grid -->
		
		<style>
		.imageInside { 
		   position: relative; 
		   width: 100%; /* for IE 6 */
		}

		h2 {
		   line-height:100px; 
		   vertical-align:middle; 
		   position: absolute; 
		   top: 0; 
		   left: 10; 
		   width: 100%; 
		}

		h2 {
			z-index:1;
		}

		h2 span { 
		   color: white; 
		   font: bold 0.8em 'montserratsemi_bold', Helvetica, Sans-Serif; 
		   letter-spacing: -1px;  
		   background: rgb(0, 0, 0); /* fallback color */
		   background: rgba(0, 0, 0, 0.7);
		   padding: 10px; 
		} 
		</style>
		
	</head>
	<body>
		
		<div class="container">
			
			<div class = "row">

				<div class="imageHolder col-md-12 middle" style="margin-top:10px;"> 

					<div class = "imageInside hvr-underline-from-center" >
						<img id = "imageHomeJPG" src="http://bit.ly/1lhHK4t" style="width:100%" />
						<h2><span>My Caption.</span></h2>
					</div>

    			</div>	
			</div>	
			
			</div>
			
		</div>
	</body>
	</html>

请全屏查看摘录以查看真实结果。

Result seen in smaller window

我使用了以下教程。 https://css-tricks.com/text-blocks-over-image/

谢谢大卫。

1 个答案:

答案 0 :(得分:0)

这就是你想要的: http://codepen.io/anon/pen/yeLjVX

诀窍来自transform属性!

 h2 {

      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
}
相关问题