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:
<body>
<div className="menu-container">
<button className="menu-trigger">
<span>Drop Down Menu</span>
</button>
<nav className="menu">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
</div>
</body>
<style>
.menu ul {
list-style: none;
}
.menu-container {
position: relative;
display: inline-block;
}
.menu {
position: absolute;
top: 100%;
}
</style>
**** Edit ****
Solved using flexbox solution:
.menu-container {
display: inline-flex;
flex-direction: column;
align-items: flex-end;
}
Advertisement
Answer
Here’s how to right-align using flexbox:
.menu-container {
width: 50%;
display: flex; /* flexbox container */
flex-direction: column; /* children in columns */
align-items: flex-end; /* children right-aligned */
background-color: #e0e0e0;
}
.menu-trigger {}
.menu {
background-color: #c0c0c0;
}
.menu ul {
list-style: none;
margin: 0 .5rem;
}<body>
<h4>Right-alignment using flexbox</h4>
<div class="menu-container">
<button class="menu-trigger">
<span>Drop Down Menu</span>
</button>
<nav class="menu">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
</div>
</body>