In this article, we will see how to centre a div on the edge of another div using SASS. SASS is an extension of CSS that stands for Syntactically Awesome Style Sheets. It helps us to create things like variables, nested rules, etc. So that we can reuse the code.
Centering a div on the edge of another div is not a difficult task. We can achieve it by using position property and bottom, top left and right properties. What we need to see is how Sass can reduce our work here.
HTML Code: In HTML, we will create two div elements. One that is outside will be called outer div and another will be called inner div.
SASS code: Sass is used to give general styling and to centring the inner div on the edge of the outer div. We create a mixin named prop with parameters for properties (height, width, background colour, and position ) so that we don’t need to write the same thing for both div elements. We can simply include this mixin and provide the value for properties. We use position property and put the left property value to 50% that will centre the inner div horizontally. The value of the bottom property is zero so that the inner div will be on the edge of the outer div.
Example 2: In this example, Centre a div on the side edge of another div. Everything in HTML will be the same. In Sass, we use the top property with a value 50% that will centre the inner div vertically and put the value of left property to zero so that the inner div will be on the side edge. Other than this piece of code rest will be the same.
Example 3 :
HTML Code: In this example, we create four div elements inside our outer div. We will see how to centre all the inner div elements on the edges of our outer div.
Sass Code: In Sass, we create a mixin called prop that we include in all div elements. Similarly mixin small div is created for all div elements inside our outer div. We create another two mixins one is verticalcentre(mixin) that is for centring the div vertically. For centring the div vertically we provide the top value to 50%. In the verticalcentre(mixin), there is an if and else condition, if the value of right is given true then the value of right property will be zero else value of the left property will be zero, which will decide on which side edge it will be on. horizontalcentre(mixin) also have the same logic, but it will centre horizontally.