How can I change the background color of divs dynamically (depending on an order-status in woocommerce)?

Your issue is a misunderstanding of how CSS/HTML works.

Take this example:

<style>p { color: red; }</style>
<p>1</p>
<style>p { color: blue; }</style>
<p>2</p>
<style>p { color: green; }</style>
<p>3</p>

Which colour is the 1st paragraph?

I suspect you would answer red, but that would be incorrect. All paragraphs are green.

The disconnect is that p { color: green; } doesn’t mean “from here onwards paragraphs are green”, it means all paragraphs on the page are green”.

What’s worse is these are inline style tags, which are very bad practice and completely unnecessary.

So instead, just add a HTML class that mentions the order status, and put rules in a CSS file to change the colours, e.g.

<div class="order-actions2 order-status--complete">
.order-status--complete {
    background-color: green;
}

In PHP you could do this:

<div class="order-actions2 order-status--<?php echo esc_attr( $order->status ); ?>">

This removes the styling part of the code from PHP entirely, simplifying things significantly, and making it much nicer to work with.

Remember, CSS rules apply globally across the entire page. .order-actions2 { ... } refers to all elements that have order-actions2 as a HTML class, regardless of where they appear on the page.

You might also be tempted to use the style="" attribute, which is also extremely very bad practice. Ignore anybody who suggests this solution.

Some extra notes:

  1. That $actions = .. line is identical in every single case, just move it to the end and call it once just before the if check
  2. There’s no reason to append . ' ' just add the space in the first string
  3. sanitize_html_class is not a substitute for esc_attr. We’re escaping here, not sanitising, so it still has to be wrapped in esc_attr