Can mathematical calculations be performed using css3?

My dilemma involves a parent element and a child element set up in the following manner:

<parent element>

    <...>

         <...>

               <child element></child element>

         </...>

     <...>

</parent element>

The challenge I face is how to make the child element inherit half of the width of its parent.

I am pondering, would it be possible in CSS3 to do something like this:

child{
    width:parent().parent().parent().width/2 + "px"
}

Unfortunately, using jQuery or adding extra code to the HTML are not options available to me. My only access is to the CSS file. Is there a solution to achieve this?

Answer №1

Not exactly the same, but a similar effect can be achieved by combining CSS variables with the calc function:

Take a look at this example utilizing variables within a parent's scope:

your_parent_element_selector{
  --ParentWidth: 100vw;
  width: var(--ParentWidth);
}

your_parent_element_selector /* ... */ your_child_selector{
  width: calc(var(--ParentWidth) / 2);
  /*simplifying calculations without units*/
  /*child inherits access to parent's variable*/
}

Here is an instance using "global" scope variables:

:root{
  /*[...]*/
  --ThisSpecificParentWidth: 100vw;
}

your_parent_element_selector{
  width: var(--ThisSpecificParentWidth);
  /*accessible through :root scope*/
}

your_parent_element_selector /* ... */ your_child_selector{
  width: calc(var(--ThisSpecificParentWidth) / 2);
}



A notable feature of the calc function is its ability to handle intricate calculations like: calc((100vw - 2em) / 2 + 10vh).

Since CSS variables act as custom properties, you can save calculation outcomes (mindful of scope) in this way:

--prop: calc((100vw - 2em) / 2 + 10vh - (var(--margin) * 2));

Answer №2

Utilizing the calc function, as mentioned correctly in previous responses, is a beneficial approach.

The calc() CSS function is applicable wherever a , , , , , or is needed. By utilizing calc(), it's possible to calculate CSS property values.

CSS calculations support various arithmetic operations including:

  • Addition.
  • Subtraction.
  • Multiplication. It's essential for at least one argument to be a .
  • Division. The right-hand side should be a .

For example:

width: calc(50% + 50px);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with the layout of a YouTube video that is embedded

Over on this particular page, an embedded YouTube video takes up the left side of the screen while a carousel labeled "Similar Festivals" sits adjacent. The code snippet used to embed the YouTube video looks something like this: This is how the YouTube se ...

Implementing Vue.js Popover for Individual Dropdown Items: A How-To Guide

I need unique information text to display for each dropdown item when hovered. I am using bootstrap-vue and have a loop set up for the dropdown items. <b-dropdown :text="currentColorType"> <b-dropdown-item v-for="colorType in co ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

Checkbox input with alphabetical ordering

I am currently facing an issue with a form that has checkboxes, but the text is not in alphabetical order. While there are plenty of examples for lists, finding examples for checkboxes has been challenging. http://jsfiddle.net/fG9qm/ <form> < ...

Issue with React app: IconMenu does not expand when clicked

Seeking assistance with a react app and IconMenu from material-ui. I've been researching similar issues extensively but haven't found a solution yet :( In the code below, I am looking to manually trigger the expansion of a menu - this is essenti ...

Encountered an error: Unexpected symbol < at the beginning of JSON data (JavaScript and PHP)

I've been struggling with this challenge for days and I hope someone can assist me with it. The issue revolves around passing data from JavaScript to PHP. My aim is to send the lostid from an HTML page to a JavaScript page, then have the JavaScript pa ...

Tampermonkey's .click() function appears to be malfunctioning

I am attempting to automate clicking a button in Tampermonkey, but for some reason the code is not working as expected. Interestingly, when I manually run the code in the console, it functions perfectly. Here is the snippet: $(document).ready(function() ...

Clearing data in a JQuery DataTable after loading it with PHP

Once the table is loaded with data, it seems to clear the information after a few milliseconds and displays a row with the message "No matching records found" https://i.sstatic.net/UPEwC.gif HTML Code <table id="table"> <thead> & ...

Exploring the Benefits of Using a Try-Catch Block for Creating an Audio Element

While reviewing the Jbox plugin code, specifically focusing on the audio addition part, I encountered the following snippet of code: jBox.prototype.audio = function(options) { options || (options = {}); jBox._audio || (jBox._audio = {}); // ...

What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given. export class CategoryIconComponent extends React.Component { static displayName = 'CategoryIcon'; state = ...

Use data attributes to automatically populate one form field with the information from another form field using jQuery

Within my Laravel 5 ecommerce website, I am attempting to automatically populate the values in the shipping_address form with the values from the billing_address form if the checkbox with name = same_as_billing is selected. I have been trying to utilize t ...

Utilize jQuery's each and map functions to create a fresh object using the data attribute as a reference

Seeking to retrieve IDs from various elements based on data attributes. Below is the HTML structure: <div class="row"> <div class="item" data-element='{"id":1, "name":"John"}'>John</div> <div class="item"></div> ...

Encountering an error when using JSONP with a period in the callback function

I am currently facing an issue with making an ajax jsonp call. It seems that the json returned contains a dot in the callback function, as shown in the example below: ABCD.render_section({ "page": { "parameters": { "pubDate": "2013-06-05 00:00:00.0", ...

Is it possible to serve CSS using relative paths that go beyond the URL root?

I've encountered a file path issue with my HTML and CSS files. My HTML file is located in: src/test/html/index.html And the corresponding CSS file is in: src/test/css/index.css In the HTML file, the CSS is linked using: <link rel="stylesheet" ...

Tips for utilizing flexbox to position a button to the right of an InputSelect

Struggling to position a button next to a dropdown? No matter what I attempt, the button keeps ending up above the dropdown. Ideally, I'd like it to appear alongside 'Select Organisation' as shown in the image below: https://i.sstatic.net/w ...

I'm wondering how to adjust the index in a loop so that it starts at 1 instead of the standard 0

Currently, I am using a .each function to create a dropdown list. As we know, the index of an array element always begins at 0 in programming. However, for my specific requirement, I need the first value in the dropdown list to start at 1 instead of 0. ...

Implement input validation in React by enhancing the functionality of HTML input tags

Below is the input provided: const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&bsol ...

Arrange list items dynamically using ajax

I am attempting to adjust the positioning of the scrollable list item depending on whether a message was sent by a user or another party. However, my current method is not yielding the desired results. I have experimented with adding .css('position&a ...

Uploading an image to the server using JQuery library and FormData

I have reviewed numerous solutions, but I am unable to identify the issue in my code. HTML: <div id='image-uploader-view'> <input type='text' id='rename' name='rename'/> <input id='fileu ...

When I include the alert('it is functioning now'); function, it operates correctly, however, it is not desired in this situation

After adding alert('now it works') to this function, it only functions correctly. However, I do not want to include this alert but the function fails without it. function a() { var ac = document.forms["myForm"]["textfield"].value; $.ajax ...