0

Hi I was trying to change the style of a pseudo element based on the screen size but i believe my syntax is wrong somewhere. I google the problem but could not find the exact solution. Below is my css-

.cBox{background-color: #efeff0; margin: 15px 0px -80px 0px;
display: inline-block;
margin-left: -8px;
margin-top: 55px;
position: relative;
width: 101%;}

.cBox:before{
border-bottom: 45px solid #efeff0;
border-left: 650px solid transparent;
border-right: 650px solid transparent;
content: "";
height: 0px;
left: 0;
position: absolute;
top: -45px;
width: 0px;}

Now the border left property of cBox:before should have half value of the screen size i.e. if screen size is 1300px, then border left should have a value of 650px(border-left:650px). below is my HTML-


 <body onload="myFunction()">
<div class="cBox"> 
<div style="text-align:center;">Some text here</div>
</div>
<script>
function myFunction(){
var x = window.getComputedStyle(document.querySelector('.cBox')
,':before').getPropertyValue('border-left');
if(window.outerWidth >=900) x[0].style.borderLeft = "screen.availWidth/2px solid transparent"; 
else {x[0].style.borderLeft = "screen.availWidth/2px solid transparent"; }
}
</script>
</body>

I know x[0].style.borderLeft syntax is not correct please suggest!
  • Possible duplicate of [Changing CSS pseudo-element styles via JavaScript](https://stackoverflow.com/questions/4481485/changing-css-pseudo-element-styles-via-javascript) – Ali Jun 03 '17 at 07:25

1 Answers1

0

Use CSS media queries to set styles for different screen sizes instead of JS.

<style>
    .cBox:before { border-left: 250px solid transparent; }

    @media(min-width: 900px) { 
        .cBox:before { border-left: 0 solid transparent; }
    }
</style>

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Modifying the style of sudo elements using JS is not possible. You can add style tags to the head though:

<script>
if (calculatedWidth > 900) {
    document.styleSheets[0].addRule('.cBox:before', 'border-left: 0 solid transparent');
}
</script>
bugs_cena
  • 495
  • 5
  • 11
  • Hi Thanks for your replay! Actually I wanted to set border-left equal to half of the screen size which is why i wanted to use js. I have updated the question again. Please have a look. – Deepjyoti Bora Jun 03 '17 at 07:30