Home > Blockchain >  Can we define width of a box in CSS dynamically?
Can we define width of a box in CSS dynamically?

Time:04-21

In django project, in views.py file we provide some data in context, and then we access it in html file using jinja templating {{...}}. But I need to use that data as pixel size for width of a box.

I am new to stackoverflow as well, so I don't know how to post views.py code. So I am writing it here.

##This is my views.py code##

from django.shortcuts import render

def home(request):

    px_size = 400

    return render(request, 'index.html', {'px_size':px_size})

##views.py code ends here##

And here is my index.html code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p{
            background-color: rgb(140, 132, 166);
            width: 400px;
            font-size: 30px;
        }
    </style>
</head>
<body>
    <p>I need to set this box's width as {{px_size}} px, dynamically</p>
    Here in body of html we can take px size from views as context. 
    <br>
    But I want to use this px_size to be the px size of width in css.
    <br>
    I have mentioned statically in style tag width as 400px.
    <br>
    How can I take it dynamically from the context?
</body>
</html>

Thanks in advance.

CodePudding user response:

Try using the aspect-ratio property. This dynamically scales based of a ratio from a given value.

So for example, if you want to use a 1/1 ratio, and assuming px_size is defined, try

        p{
            background-color: rgb(140, 132, 166);
            aspect-ratio: 1 / 1;
            width: {{px_size}};
            font-size: 30px;
        }

CodePudding user response:

<p style="width:{{px_size}}px">

CodePudding user response:

<p style="width:{{px_size}}px"></p>
  • Related