简体   繁体   English

如何在窗口中垂直和水平对齐文本?

[英]How to vertically and horizontally align text in the window?

I'm trying to center align the text both vertically and horizontally within a div in the window, and I want it to work on both portrait and landscape modes on the iPhone. 我正在尝试在窗口的div中使文本在水平和垂直方向上居中对齐,并且希望它在iPhone的纵向和横向模式下均可工作。 Here is my code but it don't work well. 这是我的代码,但效果不佳。

HTML: HTML:

<div class="mainTeaser">
    <img src="teaser.jpg" />
    <span class="teaserWrap">
        <span class="headline">TEXT</span>
        <span class="subline">TEXT</span>
    </span>
</div>

CSS: CSS:

.mainTeaser {
    position: relative;
}
.mainTeaser img {
    display: block;
    width: 100%;
}
.mainTeaser .teaserWrap {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

I would suggest to use background image instead, with background-size:cover , and use transform for centering the text. 我建议改用background background-size:cover背景图片,并使用transform将文本居中。

You'll also need to set all the containers to height:100% , so it covers the entire viewport height. 您还需要将所有容器设置为height:100% ,以使其覆盖整个视口高度。

 html, body { height :100%; margin: 0; } .mainTeaser { position: relative; height :100%; } .mainTeaser { background: url("http://lorempixel.com/300/300/nature") center center no-repeat; background-size: cover; } .mainTeaser .teaserWrap { display: block; position: absolute; top: 50%; left: 50%; -webkit-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); background: white; } 
 <div class="mainTeaser"> <span class="teaserWrap"> <span class="headline">TEXT</span> <span class="subline">TEXT</span> </span> </div> 

for Absolute to behave in that manner it needs predefined width's and height's 为了使Absolute以这种方式运行,需要预先定义的宽度和高度

see bellow in this version i just made the absolute div width 100% with text align center it leaves a little less room for error when it comes to fixed size's 在此版本中,请参见下面的波纹管,我只是使div的绝对宽度为100%,且文本居中对齐,所以在固定大小的情况下,错误的余地要少一些

 html, body { height: 100%; min-height: 100%; } .mainTeaser { position: relative; height: 100%; background-color: red; width: 100%; text-align: center; } .align { position: absolute; top: 0px; bottom: 0px; margin: auto; width: 100%; height: 35px; } .mainTeaser img { display: block; width: 100%; } .mainTeaser .teaserWrap {} 
 <div class="mainTeaser"> <div class="align"> <img src="teaser.jpg" /> <span class="teaserWrap"> <span class="headline">TEXT</span> <span class="subline">TEXT</span> </span> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM