When there is more the one rule for same element then the one with more specificity will be applied.
So, what do I mean by specificity?
It can be thought as hierarchy. Hierarchy of rules to follow, Hierarchy of CSS selectors. It can be better understood by the example:
<html>
<head>
<style>
#demo {color: blue;}
.test {color: green;}
p {color: red;}
</style>
</head>
<body>
<p id="demo" class="test">Hello World!</p>
</body>
</html>
Hello world was colored as blue, As out of all the present selectors [which are Id, class and element], "id" selector has the highest specificity.
Out of all the selectors, Inline CSS has the highest specificity, then Id, then Class, then element.
It's explained in a more elaborate way at https://www.w3schools.com/css/css_specificity.asp