all*_*tta 25 html css css3 flexbox
如何将文本居中对齐<img>
优选使用FlexBox?
body {
margin: 0px;
}
.height-100vh {
height: 100vh;
}
.center-aligned {
display: box;
display: flex;
box-align: center;
align-items: center;
box-pack: center;
justify-content: center;
}
.background-image {
position: relative;
}
.text {
position: absolute;
}
Run Code Online (Sandbox Code Playgroud)
<section class="height-100vh center-aligned">
<img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopedia/images/f/f8/Stand-out-in-the-crowd-300x300.jpg" />
<div class="text">SOME TEXT</div>
</section>
Run Code Online (Sandbox Code Playgroud)
Mic*_*l_B 25
要将文本居中于图像上,您不需要flexbox.只需使用CSS定位属性.
.height-100vh {
height: 100vh;
position: relative; /* establish nearest positioned ancestor for
absolute positioning */
}
.text {
position: absolute;
left: 50%; /* horizontal alignment */
top: 50%; /* vertical alignment */
transform: translate(-50%, -50%); /* precise centering; see link below */
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将文本在图像上垂直和水平居中:
有关定心方法的更详细说明,请参阅:
Pra*_*man 12
您可以使用relative
ly定位包装图像inline-block
<div>
并以这种方式提供文本:
* {margin: 0; padding: 0; list-style: none;}
.img-holder {position: relative; display: inline-block;}
.img-holder img {display: block;}
.img-holder p {position: absolute; top: 50%; left: 0; right: 0; transform: translate(0, -50%); text-align: center; color: #fff; text-shadow: 0 0 15px;}
Run Code Online (Sandbox Code Playgroud)
<div class="img-holder">
<img src="http://bit.ly/1YrRsis" alt="">
<p>Text Aligned Centrally Vertical & Horizontal.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
现在,这<div>
是一个inline
你可以风格的元素.
预习: