undefined
undefined

Reputation: 1148

CSS: Is there a way to apply inherited padding as negative margin?

Context

I'm using React and <td> must be clickable with <Link> of react-router-dom. Padding of <td> changes when I resize browser window because it uses css framework named Carbon. I have to <Link> = <a> tag to fit width/height of <td>. It means that when I click <td>, hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

<table>
  <tr>
    <td>
     <a href="google.com">link</a>
    </td>
  </tr>
</table>
a {
  padding: inherit;
  margin: <negative of inherited padding>
}

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

Upvotes: 1

Views: 389

Answers (3)

לבני מלכה
לבני מלכה

Reputation: 16251

Use code as below

Here I wrote an example

import React, { Component } from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      padding: 0
    };
  }

  componentDidMount() {
    const el = this.divElement;
    const style = window.getComputedStyle(el);
    const padding = style.getPropertyValue("padding").match(/\d+/);;
    this.setState({ padding });
  }

  render() {
    return (
      <table>
        <tr>
          <td>
            <a
              ref={divElement => {
                this.divElement = divElement;
              }}
              href="google.com"
              style={{margin: this.state.padding* -1 }}>
              link padding: <b>{this.state.padding}px</b>
            </a>
          </td>
        </tr>
      </table>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Upvotes: 1

retterBadach
retterBadach

Reputation: 86

Last resort javascript solution:
1) Add a resize-event listener to the window.
2) Use getComputedStyle to get the padding on resize.
3) Check console for output and adjust string to your needs.
4) Add the wanted minus sign and set the margin via the style property.

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272965

Use CSS variables to define the padding:

.box {
  --p:20px;
  padding:var(--p);
  display:inline-block;
  border:1px solid;
}

.box > a {
  margin:calc(-1*var(--p));
  padding:inherit;
  display:block;
  background:red;
}
<div class="box"><a href=""> link</a></div>
<div class="box" style="--p:30px;"><a href=""> link</a></div>
<div class="box" style="--p:10px;"><a href=""> link</a></div>

Upvotes: 0

Related Questions