user11914177
user11914177

Reputation: 965

If else statements in CSS?

I know that this question sounds similar to this one but it is different. I have two articles in a section and I want to render them side by side if the width of the window is big enough and underneath if the window width is too small.

The width of the first article is always 800 pixel and the second articles width is defined as the rest of the windows width minus all the paddings etc. So if the calculated width of the second article is too small, I just want to set it to a higher value, which will place the second article under the first article. This shouldn't be too hard if there are ifs like in other programming languages. From the question above I created this demo code for an if else statement but it doesn't work:

    @if 1 == 1 {
        border-color: #fff;
    }
    @else {
        border-color: #000;
    }

Setting to 1 == 2 which should trigger the else part still does the if part. So how can I get real if else statements?

Upvotes: 2

Views: 4074

Answers (2)

Stefan
Stefan

Reputation: 14893

CSS statements overwrite each other. So if you take this example:

body {
  background-color: green;
  background-color: red;
}

will result in the background beeing red, because it is defined later.

Now you can use this with the already mentioned media queries:

body { // your default case, if the condition is not met --> the else block
  background-color: green;
}
@media(min-width: 800px){ // here the condition is met --> if block
  body {
    background-color: red;
  }
}

Tip: you can use SCSS to make the queries way more readable.

Upvotes: 2

TinoZ
TinoZ

Reputation: 570

There are no real if/else statements in CSS, you can just use media queries and define your css depending on the width of the window like this:

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

if the window is smaller than 600px, the background color is set to lightblue. You can use several queries like min-width and max-width to define your CSS. Just have a look at: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Upvotes: 3

Related Questions