简体   繁体   English

使用CSS在容器内垂直对齐文本

[英]Vertical Align Text Inside Container with CSS

I'm pretty new to CSS and I'm trying to vertical-align: middle some text inside a div. 我是CSS的新手,我想垂直对齐:在div中插入一些文本。 This has been asked before, but I can't get any of the solutions to work for me, so I must be missing something obvious. 之前已经有人问过这个问题,但是我找不到任何适合我的解决方案,因此我肯定会缺少一些明显的东西。

I've tried: 我试过了:

Having the text in a <p> tag and in CSS adding vertical-align: middle; <p>标记和CSS中添加文本,然后添加vertical-align: middle; to the <p> tag. <p>标记。

Having the text in a <p> tag and in CSS adding vertical-align: middle; <p>标记和CSS中添加文本,然后添加vertical-align: middle; to the parent div. 到父级

Having the text in a <div class="flex-container"> and in CSS adding 将文本放在<div class="flex-container">和CSS添加中

.flex-container {
display: flex;
justify-content: center;
align-items: center;
}

As here: https://jsfiddle.net/dt3kvmdm/ 如这里: https : //jsfiddle.net/dt3kvmdm/

The parent div doesn't have a fix height in px. 父div没有以px为单位的固定高度。 Instead it's a percentage. 相反,它是一个百分比。 One solution to a similar question suggested that this could be a problem, but I'm not clear on it. 一个类似问题的解决方案表明这可能是一个问题,但我不清楚。 It would be helpful to me to be able to keep it as a percentage. 能够将其保持为百分比会对我有所帮助。

I'll be very happy to hear any suggestions! 我很高兴听到任何建议!

Thanks a lot! 非常感谢!

Nick. 缺口。

You need to use display: flex on parent element or set height: 100% on child element Fiddle 您需要在父元素上使用display: flex或在子元素上设置height: 100% Fiddle

 .ProjectTitle { background-color: green; position: absolute; width: 100%; height: 20%; bottom: 0; display: flex; justify-content: center; align-items: center; } .flex-container { font-family: "Taviraj", serif; color: #000; letter-spacing: 0.11em; } 
 <div class="ProjectTitle"> <div class="flex-container"> Project Title </div> </div> 

I'm not sure if I completely understand what you're wanting, but see if this helps: 我不确定我是否完全了解您的需求,但是请问这是否有帮助:

HTML: HTML:

<div class="ProjectTitle">
    <div class="flex-container">
        <p>Project Title</p>
    </div>
</div>

CSS: CSS:

.ProjectTitle {
    background-color: green;
    position: absolute;
    width: 100%;
    height: 20%;
    bottom: 0;
}

.flex-container {
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: "Taviraj", serif;
    color: #000;
    letter-spacing: 0.11em;
    line-height: 20%;
    height: 100%;
}

.flex-container p {
    color: #ffffff;
    vertical-align: middle;
}

Fiddle: https://jsfiddle.net/dt3kvmdm/1/ 小提琴: https : //jsfiddle.net/dt3kvmdm/1/

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

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