首页 > 解决方案 > CSS:有没有办法将继承的填充应用为负边距?

问题描述

语境

我正在使用 React,并且<td>必须可以通过<Link>react-router-dom 进行点击。<td>当我调整浏览器窗口大小时填充更改,因为它使用名为 Carbon 的 css 框架。我必须<Link>=<a>标记以适应<td>. 这意味着当我单击时<td>,超链接必须按预期工作。

问题

它可以通过负边距解决,并且应该与填充相同。但是,填充是动态的。因此,我想使用继承的填充作为负边距。

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

我不知道父级的填充,因为它是动态的。实际上,我的真实代码来自https://react.carbondesignsystem.com/?path=/story/datatable--default这是我正在使用的框架。

我该如何解决?

标签: css

解决方案


使用如下代码

这里我写了一个例子

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"));

推荐阅读