Dave Dave - 2 months ago 8
CSS Question

How do I conditionally align elements based on screen size?

I have a fairly simple header on my site:

<header>
<nav class="navbar navbar-inverse" style="">
<div class="navContainer">
<div id="navbar">
<div id="leftNavSection">
<img alt="My Logo" width="300" src="/assets/main_logo-791a416e4f99d38a339debb8dcebd7361d4172919425ace42ba2ce90336218e2.png">
</div>
<div id="rightNavSection">
Logged in as Dave A
<a href="/users/edit">Edit</a>
<a rel="nofollow" data-method="delete" href="/logout">Log Out</a>
</div>
</div>
</div>
</nav>
</header>


I align the logo to the left and the Logout links to the right:

#leftNavSection {
float: left;
}

#rightNavSection {
float: right;
}


What I would like, however, is if the screen size is small (mobile browsers), for the
Log Out
links to appear aligned to the left beneath the logo.

However, when I change the “float:right” to “float:left” this doesn’t happen. Here is my Fiddle — https://jsfiddle.net/kje3q74k/. How do I pull this off?

Answer

So here's one way to do it:

  1. Add min-width: 50% to the leftNavSection and rightNavSection.

This allows the rightNavSection to wrap to the second line on smaller displays when the content widths forces it down.

  1. Remove the default margin of body using to adjust for the 100% width of the navbar:

    body {
      margin: 0;
    }
    

    Now the wrapping will occur exactly below 600px!

  2. Float the rightNavSection to the left and align it to the right using text-align: right

    Below 600px use text-align: left using media query:

    @media only screen and (max-width: 600px) {
      #rightNavSection {
        text-align: left;
      }
    }
    

snippet below:

body {
  margin: 0;
}
header {
  overflow: hidden;
}
#navbar {
  width: 100%;
  font-family: Arial;
  vertical-align: top;
  display: inline-block;
}
#leftNavSection {
  float: left;
  min-width: 50%;
}
#rightNavSection {
  float: left;
  min-width: 50%;
  text-align: right;
}
@media only screen and (max-width: 600px) {
  #rightNavSection {
    text-align: left;
  }
}
<header>
  <nav class="navbar navbar-inverse" style="">
    <div class="navContainer">
      <div id="navbar">
        <div id="leftNavSection">
          <img alt="My Logo" width="300" src="http://placehold.it/300x300">
        </div>
        <div id="rightNavSection">
          Logged in as Dave A
          <a href="/users/edit">Edit</a>
          <a rel="nofollow" data-method="delete" href="/logout">Log Out</a>
        </div>
      </div>
    </div>
  </nav>
</header>

Hope you can take it forward from the above example. Let me know your feedback on this. Thanks!