Tyler Richardson
Tyler Richardson

Reputation: 309

How to make 1 css value dependent on another?

Im trying to make a header with three sections. (all section are lined up horizontally) I want the middle section to adjust depending on the size of the content (text) within it. When I adjust this middle size, I want the other two to adjust accordingly so that the three sections always take up the full width of the site and stay even. my site width is 1000px, this is how I have it set up

< div .side_header>  < div #header>   < div .side_header>

I want to make a script that says something along the lines of: "the width of .side_header equals (1000px minus the width of #header)*.5" This is what I wrote but my syntax is off:

<script>
    $(document).ready(function () {
        $(".side_header").css("width", "$("#header_text").css("width") * .5");  
    })
</script>

css:

        #title{

        }

        .side_header{
            display:inline-block;
            background-color:#999;
        }

        #header_text{
            display:inline-block;
            background-color:#3FF;
        }

html:

        <div id="title">
            <div class="side_header">&nbsp;</div>
            <div id="header_text"> Header text</div>
            <div class="side_header">&nbsp;</div>
        </div>

RESOLUTION: Using javascript to make dependent values can be troublesome and can result in errors easily. It is better to use a css perpricessor like .less or .sass

Upvotes: 0

Views: 2269

Answers (2)

Mahdi Mehrizi
Mahdi Mehrizi

Reputation: 217

Didn't get what you exactly want to do but just keep in mind that $.css("width") returns the CSS width of an element and not the actual width of it. So if you are trying to set the sidebars width as to occupy the rest of the page width available to them you should use $.width() to read the middle div width.

$(".side_header").css("width",((1000 - $("#header_text").width())/2) + 'px');

It is even better to use .outerWidth() as CSS wise they can be different. You can find docs about them on the following pages:

http://api.jquery.com/width/
http://api.jquery.com/outerwidth/

But after all if you want to position some div horizontally this is not a really good strategy. the width() method also works somehow not satisfactory as your CSS styling might be in a way that affects the middle div width itself. Using solid percentage width is more stable than using JS to achieve this.

Upvotes: 0

Raidri
Raidri

Reputation: 17550

You are trying to set the width to a string. Try

<script>
$(document).ready(function () {
    $(".side_header").css("width", ($(document).css("width") - $("#header_text").css("width")) * .5);  
})
</script>

Upvotes: 2

Related Questions