developer tip

CSS 클래스가 하나 이상의 다른 클래스를 상속 할 수 있습니까?

optionbox 2020. 9. 30. 10:23
반응형

CSS 클래스가 하나 이상의 다른 클래스를 상속 할 수 있습니까?


나는 오랫동안 웹 프로그래머로 일하고이 질문에 대한 답을 알지 못해 멍청하다고 느낍니다. 실제로 그것이 가능하기를 바라며 대답이 무엇인지 (가능하지 않다는 것보다) 알지 못했습니다. .

내 질문은 다른 CSS 클래스 (또는 둘 이상)에서 "상속"하는 CSS 클래스를 만들 수 있는지 여부입니다.

예를 들어,

.something { display:inline }
.else      { background:red }

내가하고 싶은 것은 다음과 같습니다.

.composite 
{
   .something;
   .else
}

".composite"클래스가 인라인으로 표시되고 배경이 빨간색 인 경우


설명하는 것과 유사한 더 높은 수준의 추상화에서 CSS를 구성 할 수있는 LESS 와 같은 도구가 있습니다 .

덜 "Mixins"라고 부릅니다.

대신에

/* CSS */
#header {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

#footer {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

넌 말할 수있다

/* LESS */
.rounded_corners {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
}

#header {
  .rounded_corners;
}

#footer {
  .rounded_corners;
}

단일 DOM 요소에 여러 클래스를 추가 할 수 있습니다.

<div class="firstClass secondClass thirdclass fourthclass"></div>

상속은 CSS 표준의 일부가 아닙니다.


예,하지만 그 구문과 정확히 일치하지는 않습니다.

.composite,
.something { display:inline }

.composite,
.else      { background:red }

공통 속성을 함께 유지하고 특정 (또는 재정의) 속성을 다시 할당합니다.

/*  ------------------------------------------------------------------------------ */   
/*  Headings */ 
/*  ------------------------------------------------------------------------------ */   
h1, h2, h3, h4
{
    font-family         : myfind-bold;
    color               : #4C4C4C;
    display:inline-block;
    width:900px;
    text-align:left;
    background-image: linear-gradient(0,   #F4F4F4, #FEFEFE);/* IE6 & IE7 */
}

h1  
{
    font-size           : 300%;
    padding             : 45px 40px 45px 0px;
}

h2
{
    font-size           : 200%;
    padding             : 30px 25px 30px 0px;
}

요소는 여러 클래스를 가질 수 있습니다.

.classOne { font-weight: bold; }
.classTwo { font-famiy:  verdana; }

<div class="classOne classTwo">
  <p>I'm bold and verdana.</p>
</div>

그리고 그것은 당신이 불행하게도 얻을 수있는 것과 거의 비슷합니다. 언젠가 클래스 별칭과 함께이 기능을보고 싶습니다.


아니 넌 할 수 없어

.composite 
{
   .something;
   .else
}

이것은 OO의 의미에서 "클래스"이름이 아닙니다. .something그리고 .else아무것도 더 단지 선택기입니다.

그러나 요소에 두 개의 클래스를 지정할 수 있습니다.

<div class="something else">...</div>

또는 다른 형태의 상속을 살펴볼 수도 있습니다.

.foo {
  background-color: white;
  color: black;
}

.bar {
  background-color: inherit;
  color: inherit;
  font-weight: normal;
}
<div class="foo">
  <p class="bar">Hello, world</p>
</div>

단락 배경색과 색상이 .foo스타일 지정된 주변 div의 설정에서 상속되는 위치입니다 . 정확한 W3C 사양을 확인해야 할 수도 있습니다. inherit어쨌든 대부분의 속성에 대한 기본값이지만 전부는 아닙니다.


이 같은 문제가 발생하여 클래스가 다른 클래스를 상속 할 수있는 것처럼 보이도록 JQuery 솔루션을 사용하게되었습니다.

<script>
    $(function(){
            $(".composite").addClass("something else");
        });
</script>

이렇게하면 "composite"클래스가있는 모든 요소를 ​​찾고 요소에 "something"및 "else"클래스를 추가합니다. 따라서 다음과 같은 결과 <div class="composite">...</div>가 나타납니다.
<div class="composite something else">...</div>


주어진 예제 SCSS 방식은 다음과 같습니다.

.something {
  display: inline
}
.else {
  background: red
}

.composite {
  @extend .something;
  @extend .else;
}

추가 정보, sass 기본 사항 확인


당신이 할 수있는 최선은 이것입니다

CSS

.car {
  font-weight: bold;
}
.benz {
  background-color: blue;
}
.toyota {
  background-color: white;
}

HTML

<div class="car benz">
  <p>I'm bold and blue.</p>
</div>
<div class="car toyota">
  <p>I'm bold and white.</p>
</div>

잊지 마세요 :

div.something.else {

    // will only style a div with both, not just one or the other

}

CSS 파일에서 :

p.Title 
{
  font-family: Arial;
  font-size: 16px;
}

p.SubTitle p.Title
{
   font-size: 12px;
}

완벽한 타이밍 : 나는이 질문에서 내 이메일로 가서 Less에 대한 기사를 찾았다 .

이후 super 단지 같은 외모 footer,하지만 다른 글꼴로, 나는 (그들이 믹스 인 호출)도 이러한 선언을 포함하도록 지시 적은의 클래스를 포함 기법을 사용합니다 :

#super {
  #footer;
  font-family: cursive;
}

나는이 질문이 이제 매우 오래되었다는 것을 알고 있지만, 여기에 아무것도 없습니다!

의도가 여러 클래스의 속성을 암시하는 단일 클래스를 기본 솔루션으로 추가하려는 경우 JavaScript / jQuery를 사용하는 것이 좋습니다 (jQuery는 실제로 필요하지는 않지만 확실히 유용합니다).

당신이있는 경우, 예를 들어 .umbrellaClass"상속"는으로부터 .baseClass1.baseClass2일부 자바 스크립트 준비에 해당하는 화재를 가질 수있다.

$(".umbrellaClass").addClass("baseClass1");
$(".umbrellaClass").addClass("baseClass2");

이제의 모든 요소 .umbrellaClass는의 모든 속성을 갖습니다 .baseClass. OOP 상속과 마찬가지로 .umbrellaClass자체 속성이있을 수도 있고 없을 수도 있습니다.

여기서 유일한주의 사항은이 코드가 실행될 때 존재하지 않는 동적으로 생성되는 요소가 있는지 여부를 고려하는 것입니다.하지만 이에 대한 간단한 방법도 있습니다.

Sucks CSS에는 네이티브 상속이 없습니다.


불행히도 CSS는 C ++, C # 또는 Java와 같은 프로그래밍 언어와 같은 방식으로 '상속'을 제공하지 않습니다. CSS 클래스를 선언 한 다음 다른 CSS 클래스로 확장 할 수 없습니다.

그러나 마크 업의 태그에 하나 이상의 클래스를 적용 할 수 있습니다.이 경우 브라우저에서 적용 할 실제 스타일을 결정하는 정교한 규칙 세트가 있습니다.

<span class="styleA styleB"> ... </span>

CSS는 마크 업을 기반으로 적용 할 수있는 모든 스타일을 찾고 여러 규칙의 CSS 스타일을 함께 결합합니다.

일반적으로 스타일은 병합되지만 충돌이 발생하면 나중에 선언 된 스타일이 일반적으로 승리합니다 (스타일 중 하나에! important 속성이 지정되지 않는 한,이 경우 승리). 또한 HTML 요소에 직접 적용된 스타일은 CSS 클래스 스타일보다 우선합니다.


http://sass-lang.com/ 에서 찾을 수있는 SASS도 있습니다 . @extend 태그와 믹스 인 유형 시스템이 있습니다. (루비)

LESS에 대한 일종의 경쟁자입니다.


이 class = "something else"와 같이 요소에 둘 이상의 CSS 클래스를 적용 할 수 있습니다.


다른 사람들이 말했듯이 요소에 여러 클래스를 추가 할 수 있습니다.

하지만 그게 핵심이 아닙니다. 상속에 대한 질문을 받았습니다. 진짜 점은 CSS의 상속이 이루어집니다한다는 것입니다 하지 수업을 통해,하지만 요소 계층 구조를 통해. 따라서 상속 된 특성을 모델링하려면 DOM의 여러 요소 수준에 적용해야합니다.


CSS에서는 불가능합니다.

CSS에서 지원되는 유일한 것은 다른 규칙보다 더 구체적입니다.

span { display:inline }
span.myclass { background: red }

"myclass"클래스가있는 범위는 두 속성을 모두 갖습니다.

또 다른 방법은 두 개의 클래스를 지정하는 것입니다.

<div class="something else">...</div>

"else"스타일은 "something"스타일을 재정의 (또는 추가)합니다.


나도 미친 듯이 찾고 있었고 다른 일을 시도하여 그것을 알아 냈습니다 : P ... 음 당신은 그렇게 할 수 있습니다 :

composite.something, composite.else
{
    blblalba
}

그것은 갑자기 나를 위해 일했습니다 :)


특정 상황에서 "소프트"상속을 수행 할 수 있습니다.

.composite
{
display:inherit;
background:inherit;
}

.something { display:inline }
.else      { background:red }

This only works if you are adding the .composite class to a child element. It is "soft" inheritance because any values not specified in .composite are not inherited obviously. Keep in mind it would still be less characters to simply write "inline" and "red" instead of "inherit".

Here is a list of properties and whether or not they do this automatically: https://www.w3.org/TR/CSS21/propidx.html


While direct inheritance isn't possible.

It is possible to use a class (or id) for a parent tag and then use CSS combinators to alter child tag behaviour from it's heirarchy.

p.test{background-color:rgba(55,55,55,0.1);}
p.test > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
<p class="test"><span>One <span>possible <span>solution <span>is <span>using <span>multiple <span>nested <span>tags</span></span></span></span></span></span></span></span></p>

I wouldn't suggest using so many spans like the example, however it's just a proof of concept. There are still many bugs that can arise when trying to apply CSS in this manner. (For example altering text-decoration types).


Actually what you're asking for exists - however it's done as add-on modules. Check out this question on Better CSS in .NET for examples.

Check out Larsenal's answer on using LESS to get an idea of what these add-ons do.


CSS doesn't really do what you're asking. If you want to write rules with that composite idea in mind, you may want to check out compass. It's a stylesheet framework which looks similar to the already mentioned Less.

It lets you do mixins and all that good business.


For those who are not satisfied with the mentioned (excellent) posts, you can use your programming skills to make a variable (PHP or whichever) and have it store the multiple class names.

That's the best hack I could come up with.

<style>
.red { color: red; }
.bold { font-weight: bold; }
</style>

<? define('DANGERTEXT','red bold'); ?>

Then apply the global variable to the element you desire rather than the class names themselves

<span class="<?=DANGERTEXT?>"> Le Champion est Ici </span>

Less and Sass are CSS pre-processors which extend CSS language in valuable ways. Just one of many improvements they offer is just the option you're looking for. There are some very good answers with Less and I will add Sass solution.

Sass has extend option which allows one class to be fully extended to another one. More about extend you can read in this article


If you want a more powerful text preprocessor than LESS, check out PPWizard:

http://dennisbareis.com/ppwizard.htm

Warning the website is truly hideous and there's a small learning curve, but it's perfect for building both CSS and HTML code via macros. I've never understood why more web coders don't use it.


Have a look at CSS compose: https://bambielli.com/til/2017-08-11-css-modules-composes/

according to them:

.serif-font {
    font-family: Georgia, serif;
}

.display {
    composes: serif-font;
    font-size: 30px;
    line-height: 35px;
}

I use it in my react project.


Don't think of css classes as object oriented classes, think of them as merely a tool among other selectors to specify which attribute classes an html element is styled by. Think of everything between the braces as the attribute class, and selectors on the left-hand side tell the elements they select to inherit attributes from the attribute class. Example:

.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}

When an element is given the attribute class="foo", it is useful to think of it not as inheriting attributes from class .foo, but from attribute class A and attribute class B. I.e., the inheritance graph is one level deep, with elements deriving from attribute classes, and the selectors specifying where the edges go, and determining precedence when there are competing attributes (similar to method resolution order).

enter image description here

The practical implication for programming is this. Say you have the style sheet given above, and want to add a new class .baz, where it should have the same font-size as .foo. The naive solution would be this:

.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
.baz { font-size : 2em; /* attribute class C, hidden dependency! */}

enter image description here

Any time I have to type something twice I get so mad! Not only do I have to write it twice, now I have no way of programatically indicating that .foo and .baz should have the same font-size, and I've created a hidden dependency! My above paradigm would suggest that I should abstract out the font-size attribute from attribute class A:

.foo, .bar, .baz { font-size : 2em; /* attribute base class for A */}
.foo, .bar { font-weight : bold; /* attribute class A */}
.foo { color : green; /* attribute class B */}

enter image description here

The main complaint here is that now I have to retype every selector from attribute class A again to specify that the elements they should select should also inherit attributes from attribute base class A. Still, the alternatives are to have to remember to edit every attribute class where there are hidden dependencies each time something changes, or to use a third party tool. The first option makes god laugh, the second makes me want to kill myself.


You can achieve what you want if you preprocess your .css files through php. ...

$something='color:red;'
$else='display:inline;';
echo '.something {'. $something .'}';
echo '.else {'. $something .'}';
echo '.somethingelse {'. $something  .$else '}';

...

참고URL : https://stackoverflow.com/questions/1065435/can-a-css-class-inherit-one-or-more-other-classes

반응형