[css] 다른 CSS 규칙 내에서 하나의 CSS 규칙을 참조 할 수 있습니까?

예를 들어 다음 HTML이있는 경우 :

<div class="someDiv"></div>

그리고이 CSS :

.opacity {
    filter:alpha(opacity=60);
    -moz-opacity:0.6;
    -khtml-opacity: 0.6;
    opacity: 0.6;
}
.radius {
    border-top-left-radius: 15px;
    border-top-right-radius: 5px;
    -moz-border-radius-topleft: 10px;
    -moz-border-radius-topright: 10px;
}

.someDiv {
    background: #000; height: 50px; width: 200px;

/*** How can I reference the opacity and radius classes here
     so this div has those generic rules applied to it as well ***/

}

스크립팅 언어에서 스크립트 상단에 자주 사용되는 일반 함수가 있고 해당 함수를 사용해야 할 때마다 매번 모든 코드를 반복하는 대신 함수를 호출하기 만하면됩니다.



답변

아니요, 한 규칙 집합을 다른 규칙 집합에서 참조 할 수 없습니다.

할 수 있습니다,하지만, 재사용 스타일 시트에서 여러 규칙 세트에 선택기 (가 하나의 규칙 세트에 여러 선택기를 사용하여 쉼표로 구분 ).

.opacity, .someDiv {
    filter:alpha(opacity=60);
    -moz-opacity:0.6;
    -khtml-opacity: 0.6;
    opacity: 0.6;
}
.radius, .someDiv {
    border-top-left-radius: 15px;
    border-top-right-radius: 5px;
    -moz-border-radius-topleft: 10px;
    -moz-border-radius-topright: 10px;
}

단일 HTML 요소에 여러 클래스를 적용 할 수도 있습니다 (클래스 속성은 공백으로 구분 된 목록을 사용함).

<div class="opacity radius">

이러한 접근 방식 중 하나가 문제를 해결해야합니다.

그것은 것 아마 도움이 설명 클래스 이름을 사용하면 요소가 대신 스타일되어야한다 방법 이 스타일되어야한다. 스타일 시트에 방법 은 그대로 둡니다 .


답변

SASS 와 같은 일종의 확장 CSS를 사용하지 않는 한 불가능합니다 . 그러나이 두 가지 추가 클래스를 적용하는 것은 매우 합리적입니다..someDiv .

.someDiv고유 한 경우 ID를 제공하고 ID를 사용하여 CSS에서 참조하도록 선택합니다.


답변

약간의 jquery를 기꺼이 사용할 수 있다면 다음과 같이 할 수 있습니다.

$('.someDiv').css([".radius", ".opacity"]);

이미 페이지를 처리하는 자바 스크립트가 있거나 <script> 태그로 묶을 수 있습니다. 그렇다면 위의 내용을 문서 준비 기능으로 감 쌉니다.

$(document).ready( function() {
  $('.someDiv').css([".radius", ".opacity"]);
}

나는 최근에 워드 프레스 플러그인을 업데이트하면서 이것을 발견했다. CSS 전반에 걸쳐 많은 “! important”지시문을 사용하여 변경되었습니다. 여러 태그에서! important를 선언하는 천재적인 결정 때문에 jquery를 사용하여 내 스타일을 강요해야했습니다.


답변

@extend를 사용하여 SASS 전처리 기로 쉽게 수행 할 수 있습니다 .

someDiv {
    @extend .opacity;
    @extend .radius;
}

아, JavaScript (jQuery)도 사용할 수 있습니다.

$('someDiv').addClass('opacity radius')

물론 가장 쉬운 방법은 HTML에 여러 클래스를 추가하는 것입니다.

<div class="opacity radius">


답변

HTML에 클래스를 추가하기 만하면됩니다.

<div class="someDiv radius opacity"></div>


답변

어제이 문제가 발생했습니다. @Quentin의 대답은 괜찮습니다.

No, you cannot reference one rule-set from another.

하지만 .Net과 같은 CSS에서 상속을 시뮬레이션하는 자바 스크립트 함수를 만들었습니다.

    var inherit_array;
    var inherit;
    inherit_array = [];
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {
            if (cssRule_i.style != null) {
                inherit = cssRule_i.style.getPropertyValue("--inherits").trim();
            } else {
                inherit = "";
            }
            if (inherit != "") {
                inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });
            }
        });
    });
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {
            if (cssRule_i.selectorText != null) {
                inherit_array.forEach(function (inherit_i, index) {
                    if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {
                        cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;
                    }
                });
            }
        });
    });

Array.prototype.includesMember = function (arr2) {
    var arr1;
    var includes;
    arr1 = this;
    includes = false;
    arr1.forEach(function (arr1_i, index) {
        if (arr2.includes(arr1_i) == true) {
            includes = true;
        }
    });
    return includes;
}

및 동등한 CSS :

.test {
    background-color: yellow;
}

.productBox, .imageBox {
    --inherits: .test;
    display: inline-block;
}

및 동등한 HTML :

<div class="imageBox"></div>

규칙이 다른 CSS 파일에 있더라도 테스트하고 나를 위해 일했습니다.

업데이트 :이 솔루션의 계층 적 상속에서 버그를 발견했으며 곧 버그를 해결하고 있습니다.


답변

var () 함수를 사용할 수 있습니다 .

var () CSS 함수를 사용하여 다른 속성 값의 일부 대신 사용자 지정 속성 값 ( “CSS 변수”라고도 함) 을 삽입 할 수 있습니다 .

예:

:root {
  --main-bg-color: yellow;
}

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: black;
  }
}

body {
  background-color: var(--main-bg-color);
}