简体   繁体   中英

How do I include input fields to a dark-mode theme in Rails 7 app with CSS?

I'm currently running Rails 7 and have a simple toggle to change to dark mode via css, following this nifty guide: https://blog.corsego.com/ruby-on-rails-dark-mode

The trouble is, it doesn't make my input fields (text fields and text areas, etc.) dark, but the font is still light, so it's unreadable.

This is my css:

 body.light {
    color: black;
    background-color: white;
  }
 body.dark {
    color: white;
    background-color: black;
  }

I've tried including dark mode for text inputs like so:

input[type=text] {
  background-color: black;
  color: white;
}

But I'm not sure how to incorporate that in with the body.dark code. Is there a way to include the inputs css with the body.dark code? I'd prefer to not have to manually edit every text input on the site with dark mode classes, if it can be avoided.

Edit:

application_controller.rb

def set_theme
    if params[:theme].present?
      theme = params[:theme].to_sym
      # session[:theme] = theme
      cookies[:theme] = theme
      redirect_to(request.referer || root_path)
    end
  end

application.html.erb

<body class="<%= cookies[:theme] %>">

  <% if cookies[:theme] == "light" %>
    <%= link_to "go dark", root_path(theme: "dark") %>
  <% else %>
    <%= link_to "go light", root_path(theme: "light") %>
  <% end %>
  
  <%= yield %>

</body>
input[type="text"] {
  background-color: black;
  color: white;
}

Try This

It turned out I was having a syntax issue when trying to specify input and input types within application.css . Here's how I fixed it:

application.css

body.dark input[type="text"] {
  background-color: black;
  color: white;
}

I also found out you can replace "text" with any specific input type, ie "email" and "password" for those specific fields. I also found out that the input variable can be modified to specify any type of html element tag, such as h1 for heading, textarea for text areas, and so on.

Also, the way this is coded ensures that the input element is nested within body so you don't need to apply it manually to every class where you have an input - it will automatically apply it wherever body persists.

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