Search code examples
htmlcsspositioning

Positioning element exactly over other element in css


I have some elements sharing certain css. Now I would like one element to have a covering div over it with some text in it. An example can be seen here. Currently it's kind of 'guessed' in place, but you can see differences between browsers so I doubt getting the pixels exactly right would change anything.

Currently, my method to get this is inserting a <div> with the same properties, but it's a lot of duplicate code and isn't perfect.

Here's the HTML:

<!-- regular non-locked element -->
<a href='#' class='level yellow'>
    <h1>Level 1</h1>
    <div class='score'>score</div>
    <h2>248</h2>
    <input type='text' value='20' class='dial' />
</a>

<!-- locked element -->
<div class='level yellow'>
    <h1>Level 1</h1>
    <div class='score'>score</div>
    <h2>0</h2>
    <input type='text' value='0' class='dial' />
    <div class='locked'><br /><br /><br />You still need to unlock this level!</div>
</div>

CSS:

.level {
    border-radius: 20px;
    -webkit-border-radius:20px;
    -moz-border-radius: 20px;
    width:150px;
    height:220px;
    padding:10px;
    border-width: 1px;
    border-style: solid;
    background-color:transparant;
    color:#8C9695;
    margin:15px auto 0px auto;
    cursor:pointer;
    position:relative;
    display:block;
    text-decoration:none;
    transition: background-color 0.3s, color 0.3s;
    -webkit-transition: background-color 0.3s, color 0.3s;
    text-align:center;
}
.level:hover:not(> .locked){
    color: white;
}
.locked {
    background-color:rgb(0, 0, 0);
    background-color:rgba(0, 0, 0, 0.8);
    width:172px;
    height:242px;
    position:relative;
    top:-135px;
    left:-10px;
    border-radius:15px;
    -webkit-border-radius:15px;
    -moz-border-radius:15px;
    z-index:20;
    cursor:default;
    transition:0.3s;
    color:transparent;
    text-align:center;
}
.locked:hover{
    color:white;
}

Solution

  • You can position elements exactly over each other by giving the underlying element position:relative and the overlay element as a child of it with position:absolute and top, right, bottom, left properties all as 0. For example:

    .level {
        position:relative;
    }
    
    .locked {
        position:absolute;
        top:0;right:0;bottom:0;left:0;
        background-color:rgb(0, 0, 0);
        background-color:rgba(0, 0, 0, 0.8);
        border-radius:15px;
        -webkit-border-radius:15px;
        -moz-border-radius:15px;
        z-index:20;
        cursor:default;
        transition:0.3s;
        color:transparent;
        text-align:center;
    }