calculate and handle margin automatically