简体   繁体   中英

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. 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; to the <p> tag.

Having the text in a <p> tag and in CSS adding vertical-align: middle; to the parent div.

Having the text in a <div class="flex-container"> and in CSS adding

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

As here: https://jsfiddle.net/dt3kvmdm/

The parent div doesn't have a fix height in 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

 .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:

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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