To change the webpage CSS styles when the device width is above a certain width and below a certain width, you have to use the media query syntax of @media
followed by writing the min-width
syntax to define the minimum width for the styles to get applied followed by writing the keyword called and
then by writing the max-width
syntax to define the maximum width so beyond the maximum width the CSS styles will not get applied.
So that the CSS styles are only getting applied only on certain width ranges (minimum and maximum width).
TL;DR
<html>
<body>
<p>Hello World!</p>
</body>
<!-- CSS styles for the `body` and `p` tag -->
<!--
Using the `min-width` and `max-width` breakpoints
to set the minimum and maximum width range
-->
<style>
body {
background-color: white;
}
p {
color: red;
}
@media (min-width: 600px) and (max-width: 800px) {
body {
background-color: black;
}
p {
color: white;
}
}
</style>
</html>
For example, let's say we have a webpage where the body
has a background color of white
and the paragraph text has the color red
.
The HTML and CSS code will look like this,
<html>
<body>
<p>Hello World!</p>
</body>
<!-- CSS styles for the `body` and `p` tag -->
<style>
body {
background-color: white;
}
p {
color: red;
}
</style>
</html>
The visual representation of the webpage with the above styles is shown below,
Now we aim to change the webpage body
background color to black
and the paragraph text color to white
when the device width is above 600px
and till the width reaches the 800px
mark. So that the 600px
mark is our minimum width for the CSS styles to get triggered and the 800px
is the maximum width the CSS styles should be triggered.
To do that, we can use the @media
synxtax followed by the (min-width: 600px)
syntax then the keyowrd and
followed by the (max-width: 800px)
syntax.
Inside this block, we can write the CSS styles to change the webpage background color to black
and the paragraph text color to white
.
It can be done like this,
<html>
<body>
<p>Hello World!</p>
</body>
<!-- CSS styles for the `body` and `p` tag -->
<!--
Using the `min-width` and `max-width` breakpoints
to set the minimum and maximum width range
-->
<style>
body {
background-color: white;
}
p {
color: red;
}
@media (min-width: 600px) and (max-width: 800px) {
body {
background-color: black;
}
p {
color: white;
}
}
</style>
</html>
Below is the visual representation of the CSS styles getting triggered only when the minimum width of the device screen matches the 600px
mark till the 800px
mark.
See the above code live in codesandbox.
That's all π.
Top comments (0)