What is the best way to center a CSS box on the screen?

I am attempting to center the login box on the screen, but when using position: absolute the background color changes to white.

/* all */

.patua_font {
    font-family: 'Patua One', cursive;
}

.Roboto_font {
    font-family: 'Roboto', sans-serif;
}


/* login css */

.cus_body {
    height: 100%;
    background: linear-gradient(to right, #31E89F, #00aff4); /*this has no effect after setting position absolute in box*/
}

.btn-primary.custom-btn {
    background-color: #00bcd4;
    border-color: #31E89F;
    width: 100%;
}

.center1 {
    text-align: center;
}

.cus_loginpad {
    padding: 4% 7%;
}

.box {
    background-color: #FAFAFA;
    width: 40%;
    min-width: 390px;
    height: auto;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 45%;
    padding: 20px 20px;
    position: absolute;
    border-radius: 5px;
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
    margin: 10px;
}

.box input {
    width: 100%;
    margin: 4px 0;
    padding: 10px;
    outline: none;
    border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>sample</title>
    <link href="https://fonts.googleapis.com/css2?family=Patua+One&family=Roboto&display=swap" rel="stylesheet">
    <link href="mainstyle.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f5eaf5f5e0f7abeff6c5b4abb4b3abb5">[email protected]</a>/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>

<body class="cus_body patua_font">
    <div class="container">
        <div class="box ">
            <div class="cus_loginpad ">
                <h2 class="center1"><img src="images/sample.png" width="150" /></h2>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
                </div>
                <div class="form-group">
                    <label for="pwd">Password</label>
                    <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
                </div>
                <button type="submit" class="btn btn-primary custom-btn"> Login </button>
            </div>
        </div>
    </div>
</body>

</html>

Is there a way to keep the background: linear-gradient(to right, #31E89F, #00aff4) while centering the login box? Thank you.

Answer №1

To achieve the desired layout, consider using the CSS property display: flex. Alternatively, you can also utilize display: grid, but flexbox is often preferred due to compatibility with older browsers like IE. If compatibility with IE is not a concern, grid layouts can be a great choice.

For detailed guidance on centering elements horizontally, vertically, or both, refer to this informative resource: center any element.

Below is an example that demonstrates how to center a box. The CSS class .container is used with flex properties for centering. Alternatively, you can create a new class specifically for centering this login-box if you prefer only certain content to be centered on your pages.

/* all */

.patua_font {
    font-family: 'Patua One', cursive;
}

.Roboto_font {
    font-family: 'Roboto', sans-serif;
}


/* login css */

.cus_body {
    height: 100%;
    background: linear-gradient(to right, #31E89F, #00aff4);
}

.btn-primary.custom-btn {
    background-color: #00bcd4;
    border-color: #31E89F;
    width: 100%;
}

.center1 {
    text-align: center;
}

.cus_loginpad {
    padding: 4% 7%;
}

.box {
    background-color: #FAFAFA;
    width: 40%;
    min-width: 390px;
    height: auto;
    left: 50%;
    top: 45%;
    padding: 20px 20px;
    border-radius: 5px;
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
    margin: 10px;
}

.box input {
    width: 100%;
    margin: 4px 0;
    padding: 10px;
    outline: none;
    border-radius: 5px;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
<!DOCTYPE html>
<html lang="en>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>sample</title>
    <link href="https://fonts.googleapis.com/css2?family=Patua+One&family=Roboto&display=swap" rel="stylesheet">
    <link href="mainstyle.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d0cfd0d0c5d28ecad3e0918e91968e90">[email protected]</a>/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>

<body class="cus_body patua_font">
    <div class="container">
        <div class="box ">
            <div class="cus_loginpad ">
                <h2 class="center1"><img src="images/sample.png" width="150" /></h2>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
                </div>
                <div class="form-group">
                    <label for="pwd">Password</label>
                    <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
                </div>
                <button type="submit" class="btn btn-primary custom-btn"> Login </button>
            </div>
        </div>
    </div>
</body>

Answer №2

Need a quick way to center your content? Use

.container{display: flex; height:100vh;}
- then simply add .box{margin: auto;} to center your box both vertically and horizontally.

For the best experience, view the following snippet in fullscreen mode to witness the magic :)

/* all */

.patua_font {
    font-family: 'Patua One', cursive;
}

.Roboto_font {
    font-family: 'Roboto', sans-serif;
}


/* login css - note I added the container stlying below */
.container {
  display: flex; 
  height: 100vh
}

.cus_body {
    height: 100%;
    background: linear-gradient(to right, #31E89F, #00aff4); /*this has no effect after setting position absolute in box*/
}

.btn-primary.custom-btn {
    background-color: #00bcd4;
    border-color: #31E89F;
    width: 100%;
}

.center1 {
    text-align: center;
}

.cus_loginpad {
    padding: 4% 7%;
}

.box {
    background-color: #FAFAFA;
    width: 40%;
    min-width: 390px;
    height: auto;
    padding: 20px 20px;
    border-radius: 5px;
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
    margin:auto; /* note that I added this*/
}

.box input {
    width: 100%;
    margin: 4px 0;
    padding: 10px;
    outline: none;
    border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>sample</title>
    <link href="https://fonts.googleapis.com/css2?family=Patua+One&family=Roboto&display=swap" rel="stylesheet">
    <link href="mainstyle.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>

<body class="cus_body patua_font">
    <div class="container">
        <div class="box ">
            <div class="cus_loginpad ">
                <h2 class="center1"><img src="images/sample.png" width="150" /></h2>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
                </div>
                <div class="form-group">
                    <label for="pwd">Password</label>
                    <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">
                </div>
                <button type="submit" class="btn btn-primary custom-btn"> Login </button>
            </div>
        </div>
    </div>
</body>

</html>

Answer №3

Similar to the suggestions above, you will require the following code:

.box {
    background-color: #FAFAFA;
    width: 40%;
    min-width: 390px;
    height: auto;

    /* You can omit the following commented out lines */
    /* transform: translate(-50%, -50%); */
    /* left: 50%; */
    /* bottom: 50%; */
    /* padding: 20px 20px; */
    
    border-radius: 5px;
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
    margin: 0 auto;
}

.cus_body {
  background-image: linear-gradient(to right, #31E89F, #00aff4); /*this is now showing */
  
  /* Ensure the parent is relatively positioned */
  /* By centering it this way, it will be responsive by default */
  position: relative;
  display: flex;
  align-items: center;
  height: 100vh;
}

For a demonstration of this code in action, visit the JSbin link below:
https://jsbin.com/fomasexala/3/edit?html,css,output

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Superimpose one element on top of another

My current page layout includes the following code: <div class="card"> <div class="card-block"> <h4 class="card-title text-muted">UltimateWarrior15</h4> <h6 class="card-subtitle text-muted"> Ad ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

"The presence of the <textarea> element is causing disruptions to the

I'm currently attempting to insert infusionsoft contact form code into a CodeBlock within the Avada theme. However, I've encountered an issue with a textarea field in the form that contains the following code: <div class="infusion-field"> ...

``There seems to be a problem regarding the alignment of elements in

Having some trouble with centering the grid on my simple website. As a beginner in Bootstrap, I'm seeking guidance. Will be grateful for any help you can offer! Please bear with me as I learn. <html> <head> <meta charset="utf8"/& ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

Tips for customizing the appearance of a child component using the parent component in Vue.js

I am working on creating a layout using Vuejs and flexbox that includes elements like 'header, sidebar, main-content, sidebar, footer'. I have separated each part of the layout into individual .vue files, such as header.vue and sidebar.vue. In ...

What is the most effective method for displaying a child modal within a map?

Project link: Check out my project here! I have two key files in my project - App.js and PageFive.js. In App.js, there is an array defined as follows: state = { boxes: [ { cbIndex: "cb1", name: "Bob" }, { cbI ...

The autocomplete feature in Jquery tagsinput is malfunctioning within a Bootstrap modal

Currently, I am working on implementing an autocomplete tag search within a bootstrap modal. The jquery library that I am using for this purpose can be found at this link. While the autocomplete search feature functions properly when the input textbox i ...

Adapting CSS according to input selection

Forgive me for asking what may seem like a simple question. I am currently using the CSS code below to modify the background color of a label when its associated checkbox is checked: #project input[id="button1"]:checked + label {background-color:red;} Is ...

Enhance Your Webpage with jQuery Drag and Drop Feature Across Multiple Lists

I've been successfully using "jQuery UI Sortable connectwith" for drag & drop functionality, as shown in the example here: . However, I now need to implement drag & drop with multiple UI elements and it's not functioning correctly. Example: < ...

What could be the reason for the child elements not being centered in a bootstrap navbar in this basic code example

Take a look at the display output by clicking here -> http://www.bootply.com/VtPTgKeCLO Below is the code snippet: <nav class="navbar navbar-fixed-bottom top-main-navbar"> <div class="container"> < ...

Resizing Your WordPress Header Logo

Hi there! I am struggling to resize the logo in the header of my website www.cookingvinyls.com. Despite my efforts, I can't seem to override the hardcoded version. I attempted to modify the width and height lines in header.php, but unfortunately, it ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Creating custom style sheets in Smarty

The formatting of a template processed in Smarty is being lost Previously (viewed in notepad++): <!DOCTYPE html> <html lang='ru'> <head> Now (displayed in the browser): <!DOCTYPE html><html lang='ru'&g ...

Inspect HTML elements using Jinja2 placeholders

I am a beginner in the world of web development, currently learning how to create Flask webapps. I am using Atom along with some addons like PreviewHTML to help me visualize live previews of my HTML code. However, I am facing an issue where I cannot see a ...

What is the best way to start with maximum padding when in full screen mode, and then gradually decrease to minimum padding as the browser width decreases?

Trying to adjust my padding with the formula padding-left: clamp( 60px, calc( value - value ), 186px) but struggling to resize it correctly as I reduce my browser width ...

Trouble with integrating jQuery Mobile data-role page into a PHP project

Why am I encountering issues when trying to link to the data role page <div data-role="page" id="sessionrecordsuccess"> in the main.php file? Instead of directing me to the specific section, it keeps redirecting to the top of main.php. I have another ...

Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, ...