Computer >> Máy Tính >  >> Lập trình >> CSS

Các phần tử trôi nổi như thế nào trong HTML?

Chúng ta có thể float các phần tử có thuộc tính float CSS ở bên trái hoặc bên phải của phần tử mẹ có chứa. Các yếu tố khác được đặt xung quanh nội dung nổi.

Nhiều phần tử có cùng giá trị của thuộc tính float được bật tất cả đều được đặt liền nhau.

Ví dụ

Hãy xem một ví dụ cho thuộc tính CSS Float -

<!DOCTYPE html>
<html>
<head>
<title>CSS Float</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
input[type="button"] {
   border-radius: 10px;
}
#container {
   display: flex;
   flex-direction: column-reverse;
   justify-content: center;
   align-items: center;
}
.child{
   height: 40px;
   width: 40px;
   color: white;
   border: 4px solid black;
}
.orange{
background-color: #FF8A00;
}
.red{
   background-color: #F44336;
}
.violet{
   background-color: #C303C3;
}
.green{
   background-color: #4CAF50;
}
.blue{
   background-color: #03A9F4;
}
.yellow{
   background-color: #FEDC11;
}
#left{
   display: flex;
   float: left;
}
#right{
   display: flex;
   float: right;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-Float</legend>
<div id="container">
<div class="child orange"></div><div class="child red"></div><div class="child violet"></div><div class="child green"></div><div class="child blue"></div><div class="child yellow"></div>
</div><br>
<input type="button" value="float-->left" onclick="floatDecider('left')">
<input type="button" value="float-->right" onclick="floatDecider('right')">
<div><div id="left"></div><div id="right"></div></div>
</fieldset>
</form>
<script>
var left = document.getElementById('left');
var right = document.getElementById('right');
function floatDecider(direction){
   var allChildren = document.getElementsByClassName('child');
   if(direction === 'left')
      left.insertAdjacentElement('beforeend',allChildren[0]);
   else
      right.insertAdjacentElement('afterbegin',allChildren[0]);
}
</script>
</body>
</html>

Đầu ra

Trước khi nhấp vào bất kỳ nút nào -

Các phần tử trôi nổi như thế nào trong HTML?

Nhấp vào ‘float -> left’ nút 4 lần -

Các phần tử trôi nổi như thế nào trong HTML?

Nhấp vào ‘float -> right’ nút -

Các phần tử trôi nổi như thế nào trong HTML?