Modify the CSS for HTML elements

70 views
Skip to first unread message

Sakshi Bansal

unread,
Aug 30, 2022, 7:27:37 AM8/30/22
to nokogiri-talk
Hello,

Is it possible to modify the CSS attributes such as 
1. Font-size, color of the headings (h1, h2, h3, p etc)
2. Border width of tables 


Mike Dalessio

unread,
Aug 30, 2022, 8:24:58 AM8/30/22
to nokogi...@googlegroups.com
Hi,

Thanks for asking this question. Yes, Nokogiri can modify any attribute on an HTML element, including `style`. You may want to try something like this ...

```ruby
#! /usr/bin/env ruby

require "nokogiri"

doc = Nokogiri::HTML5::Document.parse(File.read("foo.html"))

doc.css("h1").each do |h1_element|
  h1_element["style"] = "background-rolor: red;"
end
```

If that's not helpful for you, please share whatever code you have written so far so we can help!

-m


--
You received this message because you are subscribed to the Google Groups "nokogiri-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nokogiri-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nokogiri-talk/1f872e2f-575e-4035-b442-0f1271561c84n%40googlegroups.com.

Mike Dalessio

unread,
Aug 30, 2022, 8:28:20 AM8/30/22
to nokogi...@googlegroups.com
Or, alternatively, you can add a `style` tag to the document to do all this in CSS ...

```ruby
#! /usr/bin/env ruby

require "nokogiri"

html = <<~HTML
  <body>
    <h1 id="a">header</h1>
    <h2 id="b">another</h2>
    <h3 id="c">third</h3>
  </root>
HTML

doc = Nokogiri::HTML5::Document.parse(html)

doc.at_css("head").add_child(<<~CSS)
  <style>
    h1 {
      background-color: red;
    }
  </style>
CSS
```

Sakshi Bansal

unread,
Sep 6, 2022, 7:38:01 AM9/6/22
to nokogiri-talk
Thanks, the first solution works well. The only issue I see is that it overrides the existing styling. Is there a way to append to the existing style? 

Mike Dalessio

unread,
Sep 6, 2022, 7:52:40 AM9/6/22
to nokogiri-talk
Yes! You can append to an existing style.


It returns either a String (if the attribute already exists), or nil (if it does not exist).

So you may want to try something like:

```
h1_element["style"] ||= "" # if the value is not present (value nil) this makes it an empty string
h1_element["style"] += "background: red;"
```

If you want to get more complicated, consider injecting a style sheet (my second suggestion) and using Node#add_class (https://nokogiri.org/rdoc/Nokogiri/XML/Node.html#method-i-add_class).

Reply all
Reply to author
Forward
0 new messages