me.at.coding
me.at.coding

Reputation: 17654

Resetting margin-left on wrapping?

I am building a horizontal navigation menu using Flexbox. Items can be aligned on the left (like Home and Other item) or the right side (like About and Contact):

enter image description here

I position the About und Contact items on the right end of the flexbox by putting them inside a div with margin-left: auto. This works fine as long as no wrapping is involved. With wrapping however, it looks like this:

enter image description here

The reason is obvious with margin-left: auto being still in front of the About item. How can I ensure that when wrapping is in place, the About item also starts on the left side? Any way to reset the left margin to zero when wrapping is in place?

Code can be found in this fiddle: https://jsfiddle.net/stefan_at_wpf/b95qek8j/1/

For the archive, here's a copy of it:

The HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <link rel="stylesheet" href="mystyle.css" type="text/css" />
    </head>

    <body>
        <nav class="nav-hor">
            <a href="link1">Home</a>
            <a href="link2">Other item</a>

            <div class="right">
                <a href="link3">About</a>
                <a href="link4">Contact</a>
            </div>
        </nav>
    </body>
</html>

The CSS mystyle.css:

body {
    margin: 0px;
}

.nav-hor {
    display: flex;
    background-color: grey; 
    flex-wrap: wrap;
}

.nav-hor a {
    display: block;   
    padding: 10px;
    text-decoration: none;
    color: black;
}

.nav-hor .right {
    display: flex;
    margin-left: auto;
    flex-wrap: wrap;
}

Upvotes: 2

Views: 601

Answers (2)

Prabath Madushan
Prabath Madushan

Reputation: 31

Why dont you use css Media Query..? add this media query end of your css file and find best value for min-width

@media only screen and (max-width: 300px) {
 .nav-hor .right {
  margin-left: 0;
}

find max-width[Window width] value when wrapping is in place. hope you help this Thanks.

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272909

Move the margin auto to the second link instead. You can also remove the wrapper for the two last links:

body {
  margin: 0px;
}

.nav-hor {
  display: flex;
  background-color: grey;
  flex-wrap: wrap;
}

.nav-hor a:nth-child(2) {
  margin-right: auto;
}

.nav-hor a {
  display: block;
  padding: 10px;
  text-decoration: none;
  color: black;
}
<nav class="nav-hor">
  <a href="link1">Home</a>
  <a href="link2">Other item</a>

  <a href="link3">About</a>
  <a href="link4">Contact</a>
</nav>

Upvotes: 2

Related Questions