CSS ການເລືອກ id

id selector

id selector ສາມາດກຳນົດ style ສະແດງໃຫ້ element HTML ທີ່ມີ id ແບບສະເພາະ:

id selector ທີ່ຕິດຕາມ "#":

ໃນສອງ id selector ທີ່ມີ, ຄັ້ງທຳອິດຈະກຳນົດສີຂຽວສຳລັບ element, ຄັ້ງທີ່ສອງຈະກຳນົດສີສີຂຽວ:

#red {color:red;}
#green {color:green;}

ໃນແຊວບັນດາ HTML code ທີ່ມີ id attribute ທີ່ red, p element ຈະຖືກສະແດງໃຫ້ເປັນສີສີຂຽວ, ແລະ id attribute ທີ່ green, p element ຈະຖືກສະແດງໃຫ້ເປັນສີຂຽວ:

<p id="red">ບົວສະບັບນີ້ແມ່ນສີສີຂຽວ。</p>
<p id="green">ບົວສະບັບນີ້ແມ່ນສີຂຽວ。</p>

ເຫັນວ່າ:id attribute ຈະມີຄວາມຈິງໃນແຕ່ບັນດາ HTML document. ເກີດຂໍ້ສົນທະນາຫນັງວ່າ, ບັນຊີໄວ້ອີກຄັ້ງ: XHTML: ການປັບປຸງເວັບໄຊ.

id selector ແລະ selector ທີ່ກຳລັງໃຊ້:

ໃນການຈັດການຄອມພິວເຕີ້, id selector ໂດຍປົກກະຕິຈະນຳໃຊ້ເພື່ອສ້າງ selector ທີ່ຂາຍຢູ່:

#sidebar p {
	font-style: italic;
	text-align: right;
	margin-top: 0.5em;
	}

ແຊວບັນດາຈຸດຊະມະນະນີ້ຈະນຳໃຊ້ແຊວບັນດາຈຸດໃນສາຍ id ທີ່ sidebar. ສິ່ງນີ້ອາດຈະເປັນ div ຫຼື ການເຄື່ອງລະບົບ, ເຖິງວ່າມັນອາດຈະເປັນແຊວບັນດາອອກບັນຫາຫຼືສິ່ງອອກບັນຫາອອກທີ່ໃຫຍ່. ແຕ່ວ່ານຳໃຊ້ຄືກັບ inline element, ອອກບັນຫາ <em></em> ຫຼື <span></span>, ມັນຈະບໍ່ຖືກການນໍາໃຊ້ຍ້ອນບໍ່ສາມາດໃຊ້ <p> ພາຍໃນ inline element <span> (ຖ້າພວກເຈົ້າຈະບໍ່ຈືຂໍ້ຂັດໃຫ້, ບັນຊີໄວ້ອີກຄັ້ງ) XHTML: ການປັບປຸງເວັບໄຊ)

selector ໜຶ່ງແຕ່ນຳໃຊ້ຫຼາຍວິທີ:

ບ່ອນທີ່ຖືກແຈ້ງວ່າ sidebar ອາດຈະປະກອບຕົວໃນເອກະສານພຽງຄັ້ງດຽວແຕ່ id selector ການເລືອກກະແຈບອາດຖືກໃຊ້ຫຼາຍຄັ້ງ:

#sidebar p {
	font-style: italic;
	text-align: right;
	margin-top: 0.5em;
	}
#sidebar h2 {
	font-size: 1em;
	font-weight: normal;
	font-style: italic;
	margin: 0;
	line-height: 1.5;
	text-align: right;
	}

Here, the p elements inside sidebar are treated differently from other p elements on the page, and the h2 elements in sidebar are also treated differently from other h2 elements on the page.

Single selector

Even if the ID selector is not used to create a derived selector, it can still work independently:

#sidebar {
	border: 1px dotted #000;
	padding: 10px;
	}

According to this rule, the element with id 'sidebar' will have a black dotted border one pixel wide, and it will also have a 10 pixel wide inner padding (padding, internal blank). Older versions of Windows/IE browsers may ignore this rule unless you specifically define the element to which this selector belongs:

div#sidebar {
	border: 1px dotted #000;
	padding: 10px;
	}

Related content

If you need to learn more about ID selectors, please read the advanced tutorial on CodeW3C.com:CSS ID selector detailed.