Changing text alignment on a dropdown menu

Hi all, ex web designer here getting back into some coding after about 6 years away. I’m playing around with the W3Schools site tutorials and currently working on the sub navigation menu. My question is how do I get the menu to align to the right rather than left? I can use align: right; but that reverses the order of the menu and manually changing the order isn’t very elegant.

I’ve linked to the tryit page rather than posting the code here as it’s probably easier for anyone to provide a solution to try things out.

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_subnav

Thanks in advance.

Hi,

I wouldn’t use floats these days but flexbox instead and you can then align things how you want more easily.

You can add the flex rules to your existing code and keep the float as a fallback for older browsers like this.

body {
  font-family: Arial, Helvetica, sans-serif;
  margin: 0;
}

.navbar {
  overflow: hidden;
  background-color: #333; 
  display:flex;
  justify-content:flex-end;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.subnav {
  float: right;
  overflow: hidden;
}

.subnav .subnavbtn {
  font-size: 16px;  
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover, .subnav:hover .subnavbtn {
  background-color: red;
}

.subnav-content {
  display: none;
  position: absolute;
  left: 0;
  background-color: red;
  width: 100%;
  z-index: 1;
  justify-content:flex-end;
}

.subnav-content a {
  float: left;
  color: white;
  text-decoration: none;
}

.subnav-content a:hover {
  background-color: #eee;
  color: black;
}

.subnav:hover .subnav-content {
  display: flex;
}

NOTE: I tend to avoid hiding menu item using display:none as that removes them from search engines and screen readers. It is better to move them off screen and then bring them back into view when needed. That will also allow for transitions and animations to be applied if needed as you can’t animate from display:none.

3 Likes

Thanks Paul, that’s exactly what I was looking for.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.