将文本居中放置在柔性盒中的图像上
我怎样才能居中alignment文本<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; }
<section class="height-100vh center-aligned"> <img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopediahttp://img.dovov.comf/f8/Stand-out-in-the-crowd-300x300.jpg" /> <div class="text">SOME TEXT</div> </section>
要将文字置于图像上方,您不需要使用柔性盒。 只需使用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 */ }
修改Codepen
上面的代码将文本在图像上垂直和水平居中放置:
有关对中方法的更详细说明,请参阅:
- 元素不会居中,特别是在重新resize的屏幕时
你可以用relative
定位的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;}
<div class="img-holder"> <img src="http://bit.ly/1YrRsis" alt=""> <p>Text Aligned Centrally Vertical & Horizontal.</p> </div>
我已经添加了另一个包围img和文本的wrapper
div以及使用flex定位文本。 看到这个codepen
HTML:
<section class="height-100vh center-aligned"> <div class="wrapper"> <img class="background-image" src="http://bit.ly/1YrRsis" /> <div class="text">SOME TEXT</div> </div> </section>
CSS:
@import "bourbon"; body { margin: 0px; } .height-100vh { height: 100vh; } .center-aligned { @include display(flex); @include align-items(center); @include justify-content(center); } .wrapper { position: relative; } .text { justify-content: center; align-items: center; display: flex; color: #fff; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
您还可以使用display: inline-block;
将文本居中alignment图像display: inline-block;
到包装元素。
.height-100vh { display: inline-block; position: relative; } .text { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); color: #fff; }
<section class="height-100vh center-aligned"> <img class="background-image" src="http://vignette2.wikia.nocookie.net/uncyclopediahttp://img.dovov.comf/f8/Stand-out-in-the-crowd-300x300.jpg" /> <div class="text">SOME TEXT</div> </section>
我加了2个div
<div class="text box" > <img src="images/woodenbridge.jpg" alt="Wooden Bridge" /> <div class="slide-box flex"> <div class="flex-item"></div> </div> </div>
然后样式如下:
.flex-item { display: inline; align-self: center; }