简体   繁体   中英

How can I align a div right under another?

I created a drop-down menu in Jquery and it's working perfectly but I have only one problem with the positioning of the menu. I created the menu right after I learned about jquery animations and I'm still a beginner so I didn't follow any tutorials.

So I was wondering how can I put the menu right under the button?

<div id="nav" class="grid_5">
    <a href=""> ABOUT </a>
    <a id="products" href=""> PRODUCTS </a>
    <a href=""> HOME </a>
</div>
<div id="menu">
    <a class="menuButton" href=""> Cakes </a><br>
    <a class="menuButton" href=""> Cupcakes </a><br>
    <a class="menuButton" href=""> Fudges </a><br>
    <a class="menuButton" href=""> Ice Creams </a><br>
    <a class="menuButton" href=""> Hard Candies </a>
</div>

The menu is set under the button using an absolute position.

Here is how the site looks while full screen: 全屏显示在计算机上的图像

Here is how the site looks while windowed: 我计算机上的图像窗口化了

I would like to learn how to do this with JQuery/JScript or CSS.

You're having that problem because the menu is being position relative to the body so as the window width changes the position of the menu moves. To solve this problem you want to place your link and menu in an element with position: relative on it.

This will then mean that you can absolute position your menu relative to the container its in. So something like

<div style="position: relative">
    <div id="nav" class="grid_5">
        <a href=""> ABOUT </a>
        <a id="products" href=""> PRODUCTS </a>
        <a href=""> HOME </a>
    </div>
    <!-- When you position this absolutely it will now be relative to the container -->
    <div id="menu">
        <a class="menuButton" href=""> Cakes </a><br>
        <a class="menuButton" href=""> Cupcakes </a><br>
        <a class="menuButton" href=""> Fudges </a><br>
        <a class="menuButton" href=""> Ice Creams </a><br>
        <a class="menuButton" href=""> Hard Candies </a>
    </div>

Obviously it's better not to use inline styles and instead apply a class to the container

Wrap nav and menu div in a div and apply the position relative by which your menu div position would work accordingly:

<div class="relative">
<div id="nav" class="grid_5">
    <a href=""> ABOUT </a>
    <a id="products" href=""> PRODUCTS </a>
    <a href=""> HOME </a>
</div>
<div id="menu">
    <a class="menuButton" href=""> Cakes </a><br>
    <a class="menuButton" href=""> Cupcakes </a><br>
    <a class="menuButton" href=""> Fudges </a><br>
    <a class="menuButton" href=""> Ice Creams </a><br>
    <a class="menuButton" href=""> Hard Candies </a>
</div>
</div>

css:

.relative{
   position: relative;
}

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