简体   繁体   中英

Positioning an element consistently above a fluid image thats dead center?

I have created an overlay to display a fluid image that could be any size, what I need to do is consistently position my close button 30px above the image and at the right flush with the images edge, because I don't have a set width on the container I cant just float or position the close button where I want so wondering if anyone can suggest a different CSS approach? I know I could do this with Javascript but wondering if theres a way round using it.

CSS

body {
    box-sizing: border-box;
}

.overlay {
    position: fixed;
    top: 0; right: 0; bottom: 0; left: 0;
    margin: auto;
    background: rgba(0,0,0,.3);
}

.img-ctn {
    padding: 0;
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    margin: 0 20px;
}

.close-overlay {
    outline: none;
    border: none;
    background: grey;
    width: 40px;
    height: 40px;
}

.overlay-img {
    max-width: 100%;
    display: block;
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    margin: auto;
}

HTML

<div class="overlay">
    <div class="img-ctn">
        <button class="close-overlay"></button>
        <img src="http://lorempixel.com/output/business-q-c-1244-650-8.jpg" class="overlay-img">
    </div>
</div>

JS Fiddle http://jsfiddle.net/8kZcG/2/

We can use a vertical-align with a ghost element to centre a flexible sized container around the image and close button. Then we position the close button absolutely to this container to have it relative to the image.

HTML

<div class="overlay">
    <div class="img-container">
        <div class="img-container2">
            <button class="close-overlay"></button>
            <img src="http://lorempixel.com/business/400/200/" class="overlay-img" />
        </div>
    </div>
</div>

CSS

body {
    box-sizing: border-box;
}
.overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    background: rgba(0, 0, 0, .3);
}
.img-container {
    height: 100%;
    text-align: center;
}
.img-container:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.img-container2 {
    position: relative;
    display: inline-block;
    vertical-align: middle;
}
.close-overlay {
    outline: none;
    border: none;
    background: grey;
    width: 40px;
    height: 40px;
    position: absolute;
    right: 0;
    top: -70px;
}

Demo

Source

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