<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Centered Div</title>
<style>
.centered-div {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Adjust this value as per your needs */
}
.content {
width: 200px; /* Adjust this value as per your needs */
height: 200px; /* Adjust this value as per your needs */
background-color: #f0f0f0; /* Just for visibility */
border: 1px solid #000; /* Just for visibility */
text-align: center;
}
</style>
</head>
<body>
<div class="centered-div">
<div class="content">
Your content here
</div>
</div>
</body>
</html>
In this example, we have a parent div with the class centered-div which uses Flexbox to center its child div vertically and horizontally. The height: 100vh makes the parent div take up the full viewport height. The child div with the class content is where you would put your actual content. You can adjust the width, height, and background color as needed.
User
Now make it mobile responsive
Assistant
To make the centered div mobile responsive, we can use media queries to adjust the layout for different screen sizes. Here's the updated HTML with responsive CSS:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Centered Div</title>
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.content {
width: 100%; /* Fills the width of the parent container */
max-width: 200px; /* Adjust this value as per your needs */
padding: 20px;
box-sizing: border-box;
background-color: #f0f0f0;
border: 1px solid #000;
text-align: center;
word-wrap: break-word; /* Allows text to wrap within the container */
}
@media (min-width: 768px) {
.content {
width: 200px; /* Resumes fixed width for larger screens */
padding: 20px;
}
}
</style>
</head>
<body>
<div class="content">
Your content here
</div>
</body>
</html>
In this updated version, we removed the parent div with the centered-div class and applied the centering styles directly to the body. The content class now has a responsive width of 100% with a maximum width of 200px for mobile screens. When the screen width is at least 768px (you can change this value as per your requirements), a media query is used to set a fixed width for the content div.
This will ensure that the div remains centered and adjusts its width based on the screen size.