简体   繁体   中英

HTML/CSS center a div inside another div and make it expand

HTML looks like this

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 5</title>
<style type="text/css">

</style>
</head>
<body>
    <div id="animWrap">
        <div id="boks"></div>
    </div>
</body>
</html>

What i want to do is make the div with the id "boks" expand and "eat" the entire div "animWrap".

So my css is as following:

    body{
    margin: 0px;
}

#animWrap{
    height: 600px;
    width: 960px;
    background-color: rgb(145, 75, 75);
    margin: auto;
    position: relative;
}

#boks{
    width: 250px;
    height: 175px;
    top: 200px;
    left: 380px;
    background-color: rgb(180, 100, 100);
    position: absolute;
    transition: all 5s linear 0s;
}

#animWrap:hover #boks {
    height: 400px;
    width: 580px;
}

What i noticed is that it only expands to the right and towards the bottom. Probably because it isnt centered properly. Is there any way to expand it in every direction from the middle with only html and css?

Of course, you can do that but you have to apply a trick. Just calculate the space remaining. In this case I think the space covered by the whole div is 960px and #bok got 580px while hovering so the space at left = 190px and right = 190px. Now you can apply the hover css like this:

#animWrap:hover #boks {
    height: 400px;
    width: 580px;
    left:190px;
} 

This will do the trick and animate aligning at center. Its working in mine. Happy Coding! Cheers!!

If you you set #boks width & height respectively to 100% , and comment out it's top and left values, it should fill the entire parent div :

#boks{
    width: 100%;
    height: 100%;
    background-color: rgb(180, 100, 100);
    position: absolute;
    transition: all 5s linear 0s;
}

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