Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

html - Vertically align image inside a sticky div

I know this is a question that has been answered before but for some reason, I can't get anything to work. I have an image inside a div that is sticky. The image is currently aligned in the center horizontally but I can't get it to align in the center vertically. The image is stuck to the top of the div.

This is my HTML code:

<section>
    <div class="stickyImg img-1">
        <img src="MainImgCrop.jpeg" class="stickyImg">
    </div>
</section>

And this is my CSS code:

section {
    display: flex;
    flex-direction: row;
}

section div.stickyImg {
    height: 92vh;
    background-color: purple;
    background-size: cover;
    background-position: center;
    position: sticky;
    position: -webkit-sticky;
    top: 8vh;
    width: 50vw;
    margin: 0;
}

.stickyImg {
    width: 90%;
    height: auto;
    display: block;
    margin-right: auto;
    margin-left: auto;
    margin: auto;
    vertical-align: middle;
    top: 50%;
}

Any help would be appreciated, thank you!

question from:https://stackoverflow.com/questions/65850561/vertically-align-image-inside-a-sticky-div

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

section {
    display: flex;
    flex-direction: row;
}

section div.stickyImg {
    height: 92vh;
    background-color: purple;
    background-size: cover;
    background-position: center;
    position: sticky;
    position: -webkit-sticky;
    top: 8vh;
    width: 50vw;
    margin: 0;
    display:flex;
    flex-direction:column;
    justify-content:center;
    align-items:center;
}

.stickyImg {
    width: 90%;
    height: auto;
    display: block;
    margin-right: auto;
    margin-left: auto;
    margin: auto;
    vertical-align: middle;
    top: 50%;
}
<section>
    <div class="stickyImg img-1">
        <img src="MainImgCrop.jpeg" class="stickyImg">
    </div>
</section>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...