I am creating a dropdown menu component using React. I would like to know the CSS required to position the menu element directly under the “.menu-trigger” button, with its right border aligned to its parent’s (“.menu-container”), right border. I would like this CSS to be able to position a menu element of any reasonable size like this.
I believe I want to position the “.menu” component absolutely, relative to the parent, “.menu-container”, element.
Below is a stripped down version of html and css:
JavaScript
x
33
33
1
<body>
2
<div className="menu-container">
3
<button className="menu-trigger">
4
<span>Drop Down Menu</span>
5
</button>
6
<nav className="menu">
7
<ul>
8
<li>Item 1</li>
9
<li>Item 2</li>
10
<li>Item 3</li>
11
</ul>
12
</nav>
13
</div>
14
</body>
15
16
<style>
17
18
.menu ul {
19
list-style: none;
20
}
21
22
.menu-container {
23
position: relative;
24
display: inline-block;
25
}
26
27
.menu {
28
position: absolute;
29
top: 100%;
30
}
31
32
</style>
33
**** Edit ****
Solved using flexbox solution:
JavaScript
1
6
1
.menu-container {
2
display: inline-flex;
3
flex-direction: column;
4
align-items: flex-end;
5
}
6
Advertisement
Answer
Here’s how to right-align using flexbox:
JavaScript
1
18
18
1
.menu-container {
2
width: 50%;
3
display: flex; /* flexbox container */
4
flex-direction: column; /* children in columns */
5
align-items: flex-end; /* children right-aligned */
6
background-color: #e0e0e0;
7
}
8
9
.menu-trigger {}
10
11
.menu {
12
background-color: #c0c0c0;
13
}
14
15
.menu ul {
16
list-style: none;
17
margin: 0 .5rem;
18
}
JavaScript
1
15
15
1
<body>
2
<h4>Right-alignment using flexbox</h4>
3
<div class="menu-container">
4
<button class="menu-trigger">
5
<span>Drop Down Menu</span>
6
</button>
7
<nav class="menu">
8
<ul>
9
<li>Item 1</li>
10
<li>Item 2</li>
11
<li>Item 3</li>
12
</ul>
13
</nav>
14
</div>
15
</body>