LuckyLuke Skywalker
LuckyLuke Skywalker

Reputation: 791

How to get the property value of another element in CSS

Is there a pure-CSS way to get the property (value) of a different element or attribute?

A simple example here:

  1. h6 and button are "sister"Elements.
  2. The CSS-code-block of both are supposed to be separate.
  3. Now the previously determined font-family of h6 is supposed to be used as font-family of the button.

I don't want to unnecessarily add extra classes for this.

Another usage would be ORIENTING THE WIDTH OF AN OBJECT AT THE HEIGHT OF AN OBJECT (that is defined via % ) without using JavaScript.

Upvotes: 1

Views: 2420

Answers (3)

bt_bt_bt
bt_bt_bt

Reputation: 89

You can ensure two or more elements share a font-family without using combinators (+, , >, etc.) by using CSS custom variables. You cannot make one element directly refer to another element this way.

First, add a variable as follows to a globally-accessible selector like the root pseudo-class:

:root {
  --main-font-family: times;
}

Now, you can refer to the above value by using the syntax var(--[var-name]):

h6 {
  font-family: var(--main-font-family);
  ...
}

button {
  font-family: var(--main-font-family);
  ...
}

This approach can be helpful with more complex applications, and in my opinion can be more clear than having multiple selectors with varying specificities overriding one another.

Upvotes: 2

Bjorn.B
Bjorn.B

Reputation: 1705

With what you've described in your question, the basic nature of CSS will fit what you're asking.

  • H6 and button are siblings.
  • H6 and button are separate by the nature of HTML.
  • You will need to find the font-family of h6, and manually apply it to the button, using a css rule.

Unless of course you are asking if CSS can dynamically read an elements attributes after page load, and copy it's attributes over on it's own, in real time, then no.

h6 {
  font-family times;
  color: purple;
  font-size: 1rem;
  margin: 0;
  font-weight: normal;
}
h6, button {
  font-family: arial;  
  color: orange;
  font-size: 2rem;
}
<div class="container">
  <h6>TITLE</h6>
  <button>BUTTON</button>
</div>

Upvotes: 2

Raheel Junaid
Raheel Junaid

Reputation: 587

The only information you can "get" in CSS are the elements themselves through tags, classes, ids, attributes, etc.

You may however style elements and their siblings using the sibling selector.

h6, h6 + button {
  font-family: value;
}

You may then have separate codeblocks for the specified selectors

h6 {
  property: value;
}
button {
  property: value;
}

If you'd like to learn more about the CSS adjacent and general selectors, I would refer to this link: W3Schools Combination Selectors

Upvotes: 1

Related Questions