-1

How do I set a width to a element with a var?

I have this code:

    $(".menu_list_item").css({
        width: width + "%"
    });

But this does not seem to work.

Any help would be appreciated.

soliver
  • 319
  • 4
  • 10
  • Are you asking how to add `5px + 10%`? – James Hill Jun 23 '20 at 16:07
  • 1
    Please create a [small demo](https://stackoverflow.com/help/minimal-reproducible-example) for this using [jsfiddle](https://jsfiddle.net/) or [snippet](https://meta.stackoverflow.com/a/358993/1823841) here to show the issue happening. – palaѕн Jun 23 '20 at 16:07
  • 2
    Welcome to Stack Overflow. It is not clear where `width` is defined in your example. Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Jun 23 '20 at 16:09
  • ````let width = $(".menu_list_item").width()```` ````$(".menu_list_item").css("width", (width * 0.5) + width)````; the 0.5 is where your percent decimal will go – AttemptedMastery Jun 23 '20 at 16:13

1 Answers1

2

This is an example.

$(document).ready(function() {
  var duzina = "50%"

  $(".box").css({
    width: duzina
  });
});
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Naslov</title>
        <style>
            * {
                margin: 0px;
                height: 0px;
            }

            html, body, .container {
                width: 100%;
                height: 100%;
                background-color: red;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .box {
                height: 250px;
                background-color: orange;
            }
        </style>
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script>
            $(document).ready(function() {
                var duzina = "25%"

                $(".box").css({
                    width: duzina
                });
            });
        </script>
    </head>
    <body>
        <div class="container">
            <div class="box">
            </div>
        </div>
    </body>
</html>