Rumah >hujung hadapan web >tutorial css >Mengapa Elemen Anak Saya Tidak Menjajarkan Ke Kiri dengan 'kiri: 50%'?

Mengapa Elemen Anak Saya Tidak Menjajarkan Ke Kiri dengan 'kiri: 50%'?

Susan Sarandon
Susan Sarandonasal
2024-11-15 14:40:03521semak imbas

Why Isn't My Child Element Aligning to the Left with

CSS 'Left' Property not Aligning as Expected

When applying the "left: 50%" property to position a child element within a parent element, you may encounter cases where the child element does not align as expected. This discrepancy occurs because CSS positioning operates based on specific criteria.

Understanding Positioning in CSS

In the provided code snippet, you've specified CSS styles for two divs, "outher" (parent) and "inner" (child). The CSS for the child div includes "left: 50%", hoping to center the child's left border within the parent div. However, this approach fails due to a missing property: "position."

Adding 'Position' Property

For the "left" property to take effect, you must define the "position" property for the child div. This property specifies the positioning behavior of an element. You have two main options:

  • absolute: Removes an element from the normal flow of the document and positions it relative to its nearest positioned ancestor (such as "outher" in this case).
  • relative: Positions an element relative to its normal position in the document flow.

Revised Code Snippet

By adding the "position: absolute;" property to the child div, you can ensure that the "left: 50%" property will center the child's left border within the parent div.

#inner {
   position: absolute;
   left: 50%;
}

Demo for Visual Confirmation

Refer to the updated demo at http://jsfiddle.net/vrse2/6/ to see how the modified CSS centers the child div within the parent div as intended.

Atas ialah kandungan terperinci Mengapa Elemen Anak Saya Tidak Menjajarkan Ke Kiri dengan 'kiri: 50%'?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn