Margin vs. Padding Attributes
There is little confusion between the padding and margin attribute when you just start designing User interfaces and its web based development or Android development and the margin and padding are standard parameters to position and style User interface elements.
Both provided by extra space/gap inside or outside the container and then what’s the exact difference? Let’s get it cleared. In simple terms, the margin means to push outside and whereas padding means to push inside.
Now, let’s understand what happens when we apply these attributes for a View in Android.
Margin and Padding with a View
Let’s see how you can use these attributes with a View in android development and how it affects the View’s position and styling.
Margin → android:layout_margin
When you say push outside the view i.e the rectangle pushes its surrounding contents from itself by the dimension specified in the margin attribute / parameter and so the background contents can be other Views and the following diagram will make it clearer.
Here is how we use this is our layout XML:
android:layout_margin="20dp"
So, the other views will be differentiated from this view by at least 20dp.
We can also use different margin values for all the sides, like:
android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp"
Padding → android:padding
When you say push inside and the view i.e the rectangle pushes its contents from itself by the dimension specified in the padding attribute towards its center, so Padding can be considered as margin but inside the View and The following diagram will make it clearer.
Here is how we use this is our layout XML:
android:padding="20dp"
So, its content will be pushed inside of the rectangle by 20dp.
You can also different padding values for all the sides, like:
android:paddingRight="20dp" android:paddingLeft="20dp" android:paddingTop="20dp" android:paddingBottom="20dp"
Margin and Padding with Layout
Now, let’s understand what happens when we use these attributes for a Layout.
Margin
Whenever you say push outside and the root layout i.e the rectangle pushes its surrounding contents from itself by the dimension specified in the margin parameter / attribute. So the surrounding content will be the screen. So, the layout UI pushes itself from the screen of the mobile and The following diagram will make it clearer.
The syntax to apply margin to a layout is similar to that view.
Padding
Whenever we say push inside and the root layout i.e the rectangle pushes its contents from itself by the dimension specified in the padding attribute. So, its content will be the different views that it holds like TextView, ImageView etc. The given diagram will make it clearer.
Note:In Android the padding applied to the parent looks the same as the margin attribute applied to the child.