CSS에서 if/else 조건을 사용할 수 있습니까?
저는 CSS에 조건을 사용하고 싶습니다.
이 아이디어는 사이트가 실행되어 올바른 스타일시트를 생성할 때 내가 대신할 변수가 있다는 것입니다.
이 변수에 따라 스타일시트가 변하도록 하고 싶습니다!
다음과 같습니다.
[if {var} eq 2 ]
background-position : 150px 8px;
[else]
background-position : 4px 8px;
이거 할 수 있어요?이걸 어떻게 하나요?
전통적인 의미는 아니지만 HTML에 접근할 수 있는 경우 클래스를 사용할 수 있습니다. 예를 들어 다음과 같습니다.
<p class="normal">Text</p>
<p class="active">Text</p>
CSS 파일에는 다음과 같은 내용이 포함됩니다.
p.normal {
background-position : 150px 8px;
}
p.active {
background-position : 4px 8px;
}
그게 바로 CSS 방식입니다.
그리고 Sass와 같은 CSS 전처리기도 있습니다.조건부를 사용하면 다음과 같습니다.
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
단점은 스타일시트를 미리 처리해야 한다는 것과 실행 시간이 아닌 컴파일 시간에 조건이 평가된다는 것입니다.
CSS 속성의 새로운 기능은 사용자 지정 속성(일명 CSS 변수)입니다.실행 시(이를 지원하는 브라우저에서) 평가됩니다.
그들과 함께라면 다음과 같은 일을 할 수 있을 것입니다.
:root {
--main-bg-color: brown;
}
.one {
background-color: var(--main-bg-color);
}
.two {
background-color: black;
}
마지막으로 좋아하는 서버측 언어로 스타일시트를 전처리할 수 있습니다. PHPstyle.css.php
다,일과
p {
background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}
그러나 이 경우에는 이러한 스타일시트를 캐싱하기가 어렵기 때문에 성능에 영향을 미치게 됩니다.
좀 더 높은 수준에서, 아마드 샤이드는 이 기사에서 순수하게 CSS 내에서 UI 개발에서 종종 나타나는 질문의 유무를 결정하는 매우 유용한 기법을 많이 보여줍니다.
CSS에서 일종의 조건이기도 한 CSS 유사 클래스에 대해 아무도 언급하지 않았다는 것이 놀랍습니다.자바스크립트 한 줄 없이도 꽤 진보된 것들을 할 수 있습니다.
일부 유사 클래스:
- :active - 요소가 클릭되고 있습니까?
- : checked - 라디오/체크박스/옵션이 선택되었습니까?(체크박스를 통해 조건부 스타일링이 가능합니다.
- :empty - 요소가 비어 있습니까?
- : 전체 화면 - 문서가 전체 화면 모드입니까?
- :focus - 요소에 키보드 포커스가 있습니까?
- :focus-inside - 요소 또는 해당 요소의 자식들에게 키보드 포커스가 있습니까?
- : has([selector]) - 요소에 [selector]와 일치하는 자식이 포함되어 있습니까?(슬프게도, 어떤 주요 브라우저에서도 지원되지 않습니다.)
- :hover - 마우스가 이 요소 위로 이동합니까?
- : in-range/:out-of-range - 입력값이 min과 max limit 사이/outside인가요?
- :invalid/:valid - 양식 요소에 잘못된/유효한 내용이 있습니까?
- :link - 방문하지 않은 링크입니까?
- :not() - 셀렉터를 반전합니다.
- :target - 이 요소가 URL 조각의 대상입니까?
- : visited - 사용자가 이 링크를 방문한 적이 있습니까?
예:
div { color: white; background: red }
input:checked + div { background: green }
<input type=checkbox>Click me!
<div>Red or green?</div>
2023년 7월 업데이트:
CSS가 .@container
rsize
또 곧.style
&state
으로 if, 으로 if/합니다에 합니다.
.wrapper {
--something: 1;
}
@container style(--something: 1) {
.foo {...}
}
@container
) )리:
- 실제 컨테이너 요소가 필요합니다.
- 쿼리 조건은 "자체"에 적용되지 않습니다(부모 중 한 명만 해당).
저는 CSS-Tricks에서 아래의 고유한 방법에 대한 글을 작성하였는데, 이는 좀 더 자세히 설명합니다.
시뮬레이션을 할 수 있는 다양한 트릭을 사용하여 아래 데모를 고안했습니다. if/else
일부 속성에 대한 시나리오입니다.본질적으로 수치화된 속성은 이 메서드의 대상이 되지만 텍스트 값을 가진 속성은 대상이 됩니다.
이 코드는 3개입니다.if/else
오,opacity
,background color
&width
지배됩니다. 3개의 2개의 부울 변수.bool
그 반대대.notBool
.
이 두 개의 부울은 이 방법의 핵심이며, 부울이 아닌 동적 값에서 부울을 얻기 위해서는 운 좋게도 CSS가 & 함수를 사용할 수 있는 수학이 필요합니다.
분명히 이러한 기능(min/max)은 CSS 사용자 지정 속성(변수)도 지원하는 최신 브라우저 버전에서 지원됩니다.
var elm = document.querySelector('div')
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: lightgreen;
--color2: salmon;
--width: 70; /* starting value, randomly changed by javascript every 1 second */
}
div{
--widthThreshold: 50;
--is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
--is-width-below-limit: calc(1 - var(--is-width-above-limit));
--opacity-wide: .4; /* if width is ABOVE 50 */
--radius-narrow: 10px; /* if width is BELOW 50 */
--radius-wide: 60px; /* if width is ABOVE 50 */
--height-narrow: 80px; /* if width is ABOVE 50 */
--height-wide: 160px; /* if width is ABOVE 50 */
--radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
--opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
--colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
--height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
height: var(--height);
text-align: center;
line-height: var(--height);
width: calc(var(--width) * 1%);
opacity: var(--opacityToggle);
border-radius: var(--radiusToggle);
background: linear-gradient(var(--colorsToggle));
transition: .3s;
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"%";
}
div::after{
counter-reset: bb var(--is-width-above-limit);
content: " is over 50% ? "counter(bb);
}
<div></div>
를 또 다른 clamp
:
label{ --width: 150 }
input:checked + div{ --width: 400 }
div{
--isWide: Clamp(0, (var(--width) - 150) * 99999, 1);
width: calc(var(--width) * 1px);
height: 150px;
border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
background: lightgreen;
}
<label>
<input type='checkbox' hidden>
<div>Click to toggle width</div>
</label>
지금까지 최고:
2020년 10월 업데이트 - 특정 유형의 계산이 필요한 일부 상황에서 이 방법에 영향을 미칠 수 있는 크롬 버그를 발견했지만 해결 방법이 있습니다.
2023년 6월 업데이트 - Chrome regression(크롬 회귀) 문제로 인해 보고서를 제출하여 작동이 중지되었습니다.
저는 완전히 독특한 방법을 생각해 냈는데, 그것은 더 간단해요!
하여 paused
&duration
, / 할 수 .0%
- 가duration
0s
않는 더 큰을 가진 면,다해) paused
).
var elm = document.querySelector('div')
// random number between 20 & 80
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: salmon;
--color2: lightgreen;
}
@keyframes wide-container-frames{
0%{
--height: 160px;
--radius: 30px;
--color: var(--color2);
opacity: .4; /* consider this as additional, never-before, style */
}
}
@keyframes wide-container-frames--after{
0%{
content: "true";
color: green;
}
}
div{
--width: 70; /* must be unitless */
--height: 80px;
--radius: 0px;
--color: var(--color1);
--widthThreshold: 50;
--is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));
font: 22px Roboto, Arial;
text-align: center;
white-space: nowrap;
/* if element is narrower than --widthThreshold */
width: calc(var(--width) * 1%);
height: var(--height);
line-height: var(--height);
border-radius: var(--radius);
background: var(--color);
/* else */
animation: wide-container-frames calc(var(--is-width-over-threshold) * 1s) paused;
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"% is over 50% width ? ";
}
div::after{
content: 'false';
font-weight: bold;
color: darkred;
/* if element is wider than --widthThreshold */
animation: wide-container-frames--after calc(var(--is-width-over-threshold) * 1s) paused;
}
<div></div>
합니다.calc()
var()
조건을 모방하는 방법:
:root {
--var-eq-two: 0;
}
.var-eq-two {
--var-eq-two: 1;
}
.block {
background-position: calc(
150px * var(--var-eq-two) +
4px * (1 - var(--var-eq-two))
) 8px;
}
아래는 여전히 유효한 이전 답변이지만 오늘은 좀 더 의견을 제시하는 접근 방식입니다.
CSS가 그렇게 썩 좋은 이유 중 하나는 정확히 조건부 구문이 없기 때문입니다.CSS는 현대적인 웹 스택에서 완전히 사용할 수 없습니다.조금만 SASS를 사용하면 제가 왜 그런 말을 하는지 알 수 있을 겁니다.SASS에 조건부 구문이 있습니다...원시 CSS에 비해 많은 다른 장점들도 있습니다.
이전 답변(계속 유효):
일반적으로 CSS에서는 할 수 없습니다!
브라우저 조건은 다음과 같습니다.
/*[if IE]*/
body {height:100%;}
/*[endif]*/
그러나 누구도 자바스크립트를 사용하여 DOM을 변경하거나 클래스를 동적으로 할당하거나 각자의 프로그래밍 언어에서 스타일을 연결하는 것을 방해하지 않습니다.
저는 때때로 CSS 클래스를 문자열로 뷰에 보내고 코드에 이를 반향합니다(php).
<div id="myid" class="<?php echo $this->cssClass; ?>">content</div>
두 개의 개별 스타일시트를 생성하고 비교 결과에 따라 하나를 포함할 수 있습니다.
네가 넣을 수 있는 것 중 하나에
background-position : 150px 8px;
다른 하나는
background-position : 4px 8px;
CSS에서 수행할 수 있는 유일한 검사는 브라우저 인식뿐이라고 생각합니다.
CSS는 잘 설계된 패러다임이며, 많은 기능이 많이 사용되지 않습니다.
조건과 변수에 의해 문서 전체에 또는 요소의 범위에 따라 일부 값의 변경을 분배하는 메커니즘을 의미하는 경우, 다음과 같은 작업을 수행 방법은 다음과 같습니다.
var myVar = 4;
document.body.className = (myVar == 5 ? "active" : "normal");
body.active .menuItem {
background-position : 150px 8px;
background-color: black;
}
body.normal .menuItem {
background-position : 4px 8px;
background-color: green;
}
<body>
<div class="menuItem"></div>
</body>
이렇게 하면 변수의 영향을 CSS 스타일 전체에 분산시킵니다.이것은 @amichai와 @SeReGa가 제안하는 것과 비슷하지만, 더 다용도적입니다.
다른 방법은 일부 활성 항목의 ID를 문서 전체에 분산시키는 것입니다. 예를 들어, 메뉴를 다시 강조 표시할 때: (프리마커 구문 사용)
var chosenCategory = 15;
document.body.className = "category" + chosenCategory;
<#list categories as cat >
body.category${cat.id} .menuItem { font-weight: bold; }
</#list>
<body>
<div class="menuItem"></div>
</body>
물론, 이것은 카테고리나 주와 같은 제한된 품목 세트에서만 실용적이며, e-shop 상품과 같은 무제한 세트에서는 그렇지 않으면 생성된 CSS가 너무 클 것입니다.그러나 정적 오프라인 문서를 생성할 때 특히 편리합니다.
CSS를 생성 플랫폼과 결합하여 "조건"을 수행하는 또 다른 방법은 다음과 같습니다.
.myList {
/* Default list formatting */
}
.myList.count0 {
/* Hide the list when there is no item. */
display: none;
}
.myList.count1 {
/* Special treatment if there is just 1 item */
color: gray;
}
<ul class="myList count${items.size()}">
<!-- Iterate list's items here -->
<li>Something...</div>
</ul>
좋아요 대신 사용할 수 없습니다.
.Container *:not(a)
{
color: #fff;
}
css 파일을 PHP로 파싱하도록 서버를 설정한 후 간단한 PHP 문으로 변수를 정의합니다.
물론 이것은 당신이 PHP를 사용하고 있다고 가정합니다...
이것은 위의 볼드윈 답변에 대한 약간의 추가 정보입니다.
if/else를 수행하기 위해 php 코드를 추가합니다.
if($x==1){
print "<p class=\"normal\">Text</p>\n";
} else {
print "<p class=\"active\">Text</p>\n";
}
CSS에는 조건부 규칙이라는 기능이 있습니다.CSS의 이 기능은 특정 조건에 따라 적용됩니다.조건부 규칙은 다음과 같습니다.
- @ @
- @매체
- @ @
구문:
@supports ("condition") {
/* your css style */
}
코드 조각 예제:
<!DOCTYPE html>
<html>
<head>
<title>Supports Rule</title>
<style>
@supports (display: block) {
section h1 {
background-color: pink;
color: white;
}
section h2 {
background-color: pink;
color: black;
}
}
</style>
</head>
<body>
<section>
<h1>Stackoverflow</h1>
<h2>Stackoverflow</h2>
</section>
</body>
</html>
css에는 if/then/selse가 없는 것으로 알고 있습니다.또는 javascript 함수를 사용하여 요소의 배경 위치 속성을 변경할 수 있습니다.
그러나 (문을 동적으로 평가할 것인지 여부에 따라) 또 다른 옵션은 여기에 설명된 것처럼 C 전처리기를 사용하는 것입니다.
javascript는 다음과 같은 용도로 사용할 수 있습니다.
- 먼저 '일반' 클래스와 '활성' 클래스의 CSS를 설정합니다.
- 그러면 당신은 당신의 원소에게 '나의 원소'라는 아이디를 줍니다.
- 이제 자바스크립트로 조건을 만들어 보세요. 아래의 예와 같은 것 말이죠.(실행할 수 있으며 myVar 값을 5로 변경하면 작동 방식을 볼 수 있습니다.)
var myVar = 4;
if(myVar == 5){
document.getElementById("MyElement").className = "active";
}
else{
document.getElementById("MyElement").className = "normal";
}
.active{
background-position : 150px 8px;
background-color: black;
}
.normal{
background-position : 4px 8px;
background-color: green;
}
div{
width: 100px;
height: 100px;
}
<div id="MyElement">
</div>
모든 조건 범위에 대해 컨테이너 div를 추가할 수 있습니다.
container div. (server side programming - php/asp...)로 조건값을 클래스로 추가합니다.
<!--container div-->
<div class="true-value">
<!-- your content -->
<p>my content</p>
<p>my content</p>
<p>my content</p>
</div>
이제 컨테이너 클래스를 각 요소에 추가하지 않고 중첩 선택기를 사용하여 분할의 모든 요소에 대해 전역 변수로 사용할 수 있습니다.
.true-value p{
background-color:green;
}
.false-value p{
background-color:red;
}
곧 에를 할 수 또 다른 , .if/else
스크립트 더다를 합니다.@when
/@else
조건부의이러한 조건은 쉽게 인식할 수 있는 논리 체인을 실행하기 위해 구현됩니다. 예를 들어 다음과 같습니다.
@when supports(display: flex) {
.container {
display: flex
}
} @else media and (min-width: 768px) {
.container {
min-width: 768px
}
} @else {
.container {
width: 100%
}
}
2022년 2월 현재 브라우저 지원은 없습니다.자세한 내용은 이 W3C 모듈을 참조하시기 바랍니다.
(네, 오래된 실입니다.하지만 구글 검색을 통해 다른 사람들도 관심을 가질 수 있습니다.)
if/else-logic은 javascript로 할 수 있을 것 같습니다. 그러면 스타일시트를 동적으로 로드/언로드할 수 있습니다.브라우저 등을 통해 테스트해 본 적은 없지만 작동할 것입니다.그러면 시작할 수 있습니다.
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
jquery를 사용할 수 있는 경우 html 내에서 javascript를 사용하여 조건문을 설정할 수 있습니다.
$('.class').css("color",((Variable > 0) ? "#009933":"#000"));
텍스트 색상이 변경됩니다..class
변수 값이 다음보다 크면 녹색으로 표시합니다.0
.
One option that doesn't seem mentioned in the other answers would be an attribute selector. You could set e.g. a data attribute on a div tag
<div data-var="2">
and then define a selector for divs with the right attribute value as the if case, and a div selector without an attribute selector for the else case:
div[data-var="2"] {
background-position : 150px 8px;
}
div {
background-position : 4px 8px;
}
ReferenceURL : https://stackoverflow.com/questions/1129699/can-you-use-if-else-conditions-in-css
'programing' 카테고리의 다른 글
jQuery를 사용하여 원소의 위쪽에서 px로 수직 거리를 찾는 방법 (0) | 2023.09.28 |
---|---|
Sequelize User M2M Group - 그룹에 속한 사용자 찾기 (0) | 2023.09.28 |
스파크 데이터 프레임을 만듭니다.유형에 대한 스키마를 유추할 수 없습니다. (0) | 2023.09.23 |
"inti = 1;왜 (i > = 60 * 60 * 1000 / 1 * 1000)"가 참입니까? (0) | 2023.09.23 |
Oracle 10g Express 홈 페이지가 뜨지 않습니다. (0) | 2023.09.23 |