简体   繁体   English

CSS将div与动态内容垂直对齐

[英]CSS align div vertically with dynamic content

I have the following markup: 我有以下标记:

<div class="content-one yellow" style="min-height: 365px;">
    <div class="content-one-inner">
        <div class="left">
            <div class="img-wrapper">
                <img src="" alt="Accenture tshirt">
            </div>  
        </div>
        <div class="right">
            <h1 class="desktop">
                <span class="lev-1">
                    <span>CREATE</span> 
                    <span>YOUR</span>
                </span>
                <span class="lev-2">
                    <span>UNIQUE</span> 
                    <span>TEE</span>
                </span>
            </h1>
            <div class="text-wrapper">
                <p> </p>
                <p></p>
                <p></p>
            </div>
            <a class="next" href=""><span>Build your design</span></a>
        </div>
    </div>
</div>

content-one has a min-height calculated by JS which gets the height of the screen like so: content-one具有由JS计算的min-heightmin-height如下所示获取屏幕的高度:

$(document).ready(function(){
    function updateWindowHeight () {
        var currentHeight = $(window).height();
        $('.content-one').css('min-height', currentHeight - 132);
    }

    updateWindowHeight();

    $(window).on('resize', function(){
        updateWindowHeight();
    });
});

I then have a CSS rule like so: 然后,我有一个CSS规则,如下所示:

.content-one .content-one-inner {
    margin: 0 0 0 4px;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    width: 90%;
}

This centers the div correctly however if the content of it increases or the screen is smaller in height then the .content-one-inner gets hidden under the header rand footer. 这样可以正确地使div居中,但是,如果div的内容增加或屏幕的高度变小,则.content-one-inner会隐藏在页眉rand页脚下。

How can I write my css that if the screen is smaller or the content increases the div (content-one) is still centered but hidden under header and footer? 我如何写CSS,如果屏幕较小或内容增加,则div(内容一)仍居中但隐藏在页眉和页脚下?

As flexbox evangelist I would suggest flexbox :) 作为flexbox传播者,我建议flexbox :)

Then we will need to add code directly to the parent so div.content-one , which would look like this 然后,我们将需要直接向parent添加代码div.content-one ,如下所示

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

Here comes codePen with solution 这是带有解决方案的codePen

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

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