jquery - 将 H2 Span 垂直对齐到 DIV 的中心

标签 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/

谢谢,大卫。

最佳答案

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

诀窍来自变换属性!

 h2 {

      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
}

关于jquery - 将 H2 Span 垂直对齐到 DIV 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103866/

相关文章:

javascript - 单击时更改 div 样式不起作用

jquery - 同位素不适用于 ajax 加载的内容

javascript - 需要两次页面刷新才能从MySQL数据库获取输入数据

javascript - 在包含图像的 Div 上设置 EventListener 不触发功能

html - 为什么我的 block 与行的底部对齐? (CSS/HTML)

javascript - 我可以让 &lt;input type=text> 看起来像 &lt;input type=password> 吗?

jQuery:从表 td 中找到最长的字符串

jquery - 使用 jQuery 一次切换一项

javascript - 为什么自动播放不能在使用 html5 音频的页面刷新时工作?

css - 即使我设置了 html 字体大小,REM 大小也不会更新