Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งาน Property margin-bottom ใน CSS

บทนำ

Property margin-bottom ระบุระยะห่างด้านล่างของ element คล้ายกับ margin-top แต่เป็นด้านล่าง

ตัวอย่างโค้ด

<html>
<head></head>
<body>
  <p style="margin-bottom: 20px; border:2px solid red;">
    This is a paragraph with a specified bottom margin.
  </p>
  <p style="margin-top: 20%; border:2px solid green;">
    This is another paragraph with a specified top margin in percent.
  </p>
</body>
</html>

รายละเอียดค่า

หน่วยคำอธิบายเหมาะสำหรับ
pxพิกเซล คงที่Layout แบบคงที่
emสัมพันธ์กับ font-size ของ elementTypography, spacing ที่ scale ตาม font
remสัมพันธ์กับ font-size ของ root (html)Design system, consistent spacing
%เปอร์เซ็นต์ของความกว้าง containing blockResponsive layout
autoเบราว์เซอร์ตัดสินใจ (มักเป็น 0)Centering (กับ margin-left/right auto)

Margin Shorthand

/* 4 ค่า: top right bottom left */
margin: 10px 20px 30px 40px;

/* 3 ค่า: top right/left bottom */
margin: 10px 20px 30px;

/* 2 ค่า: top/bottom right/left */
margin: 10px 20px;

/* 1 ค่า: ทุกด้าน */
margin: 10px;

/* เฉพาะด้านล่าง */
margin-bottom: 20px;

Margin Collapsing ตัวอย่าง

<style>
  .box1 { margin-bottom: 50px; background: #ffcccc; }
  .box2 { margin-top: 30px; background: #ccffcc; }
</style>

<div class="box1">Box 1 (margin-bottom: 50px)</div>
<div class="box2">Box 2 (margin-top: 30px)</div>
<!-- ระยะห่าง = 50px (max of 50, 30) -->

ป้องกัน Margin Collapsing

  • เพิ่ม overflow: hidden หรือ overflow: auto ให้ parent
  • เพิ่ม padding หรือ border ให้ parent
  • ใช้ display: flex หรือ display: grid ให้ parent