CSS Why left rule is given precedence over right rule when there’s a width?

后端 未结 5 588
生来不讨喜
生来不讨喜 2020-12-21 11:52

I have this CSS code:

#div1{
 height:200px;
 width:200px;
 background-color:red;
 position:absolute;
 right:30px !important; 
 left:0px;
 }

5条回答
  •  爱一瞬间的悲伤
    2020-12-21 12:33

    Programming/Coding is all about doing things logically and making life easy.
    To answer your question in a simple way, I would say that - You might be thinking that right:30px; should override left:0; deu to specificity and cascading rule, right? But not here, cascading happens when your both property are same. So, if you write:

    width: 30px;
    width: 50px !important;
    

    width: 50px is going to get applied.

    But in your case, it's left vs right. Not the same property. So, when CSS encounters both of these values, it thinks logically and apply the values. Because if you wanted the element to position just 30px left, you could have written left: 30px; and if you wanted the element to position just 30px right, you could have written right: 30px; but not both the values in either of the case.

    I think you got my point and hope that helps clear your confusion. :)

提交回复
热议问题