Để căn giữa một phần tử theo chiều dọc và chiều ngang bằng CSS, mã như sau -
Ví dụ
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.centered {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid rgb(0, 70, 128);
}
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<h2>This text is centered vertically and horizontally both</h2>
</div>
</body>
</html> Đầu ra
Đoạn mã trên sẽ tạo ra kết quả sau -