简体   繁体   中英

Ruby on Rails each method and divs

Okay so I have this code

<% @users.each_with_index do |user, index| %>
  <p><%= user.name %></p>
  <% if (index + 1) % 5 == 0 %>
    <div class="clearfix visible-xs"></div>
  <% end %>
<% end %>

Which says after every 5th item. Add a clearfix. Great. But I am using bootsrap and trying to make this responsive. Code works great in full screen. But then I resize it and I need to put the <div class="clearfix visible-xs"></div> after every 3rd, for example, item instead of 5th.

Anyone have any ideas on what I can do to solve this?

This will be a CSS issue rather than Rails

--

CSS

You should look up about @media queries in CSS - these change depending on what screen size you're currently running (and are dynamic). Rails is just there to render the HTML, not implicate the styling

The most elegant solution will be to create a single class, which will then adapt as the media queries change - which I'd do this way:

<div class="users">
  <% @users.each_with_index do |user, index| %>
    <li><%= user.name %></li>
    <% if (index + 1) % 5 == 0 %>
      <div class="clearfix visible-xs"></div>
    <% end %>
  <% end %>
</div>

#app/assets/stylesheets/application.css.scss
.users {
   li:nth-child(5) {
      &:after {
         //clearfix styling
      }
   }
}

@media (max-width: 600px) {
      li:nth-child(3) {
         &:after {
           #clearfix code
         }
      }
      li:nth-child(5) {
         &:after {
           display: none
         }
      }
   }
}

This may look somewhat complicated (you could clear it up by using pure SASS) - what I'm trying to recommend is that you look at your styling rather than your rendering mechanism to determine the fix.

You're really looking at a responsive design - meaning it needs to adapt dynamically to your calls. This is not within the scope of rails; it's CSS

Add another if-condition for % 3 with div.visible-lg

<% @users.each_with_index do |user, index| %>
  <p><%= user.name %></p>
  <% if (index + 1) % 3 == 0 %>
    <div class="clearfix visible-lg"></div>
  <% end %>
  <% if (index + 1) % 5 == 0 %>
    <div class="clearfix visible-xs"></div>
  <% end %>
<% end %>

But, yes, it's not an elegant solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM