`Some button elements are unable to center properly within a div tag in HTML`

I am in the process of developing a website for my school project and have encountered an issue that I cannot seem to resolve despite exhausting all possible resources. As a beginner in HTML and CSS, I hope my query is not deemed trivial. My webpage layout consists of a row with two columns - the left one and the right one. The text in the right column aligns perfectly to the center using display: flex and justify-content: center, but the button within the same column refuses to cooperate. While I can adjust the margins manually, the button fails to adapt when resizing the page.

Below is a snippet of the code in question:

@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap");

/* ---- Set up site grid ---- */

@media (max-width: 600px) {
  .left,
  .right {
    width: 100%;
  }
}

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
} 

body {
  background: gray;
  font-family: "Montserrat", sans-serif;
}

main {
  grid-area: main;
  background: #272727;
}
.... (trimmed for brevity)
</ul>

      <button class="btnQuiz">Take Quiz</button>

    </div>

  </div>

</main>

I apologize for including unrelated CSS in the snippet. However, I trust that you grasp my dilemma, and I welcome any insights or solutions you may have to offer.

Answer №1

You can easily center a button using this code snippet.

.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div class="center">
  <button>Centered Button</button>
</div>

Answer №2

**Give this code a shot and hopefully it solves your problem.**
**Modify button CSS styling**
.btnQuiz{
 font-family: "Montserrat", sans-serif;
  background-color: #ffe31c;
  border-radius: 10px;
  border: none;
  color: black;
  text-align: center;
  text-decoration: none;font-size: 16px;
  display: flex;
}

**New changes applied**
.btnQuiz{  
 font-family: "Montserrat", sans-serif;
  background-color: #ffe31c;
  border-radius: 10px;
  border: none;
  color: black;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  display: flex;
  margin: 0;
  position: absolute;
  top: 50%;
  left: 75%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>    @import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap");
    /* ---- Setting up the site grid layout for responsiveness ---- */

    @media (max-width: 600px) {
      .left, .right{
        width: 100%;
      }
    }

    * {
      margin: 0;
      padding: 0;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }



    body {
      background: gray;
      font-family: "Montserrat", sans-serif;
    }








    main{
        grid-area: main;
        background: #272727;
        
        
        
    }



    footer{
        grid-area: footer;
        background-color: black;
        text-align: right;
        color: white;
    }




    h1.titleH1 {
        font-family: 'Montserrat', sans-serif;  
        font-size: 2.3vw;
        padding-left: 150px;
        margin: auto;
        color: white;
            
        /* -- Vertically centering the heading -- */
        position: relative;
        top: 50%;
        transform: translateY(-50%);
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        
        }

    img.roundleft{
        border-top-left-radius: 10px;
        border-bottom-left-radius: 10px;
        box-shadow: 1px 0px 10px #000;
        float: left;
    }




    /*--- Navigation Bar ---*/

    .wrapper{
      display: grid;
      grid-template-areas:
        'headerLeft headerRight';

      grid-template-columns: 600px 1fr;

      
              
    }

    .headerLeft{
      text-align: left;
      background-color: black;
    }

    .headerRight{
      text-align: right;
     background: linear-gradient(to left,#55524e, black);
    }


    .navMenu {
      margin-top: 30px;
      margin-right: 20px;
       
      
    }

    .navMenu a {
      color: #f6f4e6;
      text-decoration: none;
      font-size: 1vw;
      text-transform: uppercase;
      font-weight: 500;
      margin-left: 50px;
      margin-right: 50px;
      -webkit-transition: all 0.2s ease-in-out;
      transition: all 0.2s ease-i n-out;
    }

    .navMenu a:hover {
      color: #fddb3a;
    }



    /*---- Main Pages (Rows and Columns) ----*/

    .row{
      display: flex;

    }

    .column
    {
      height: 800px;
    }

    .left
    {
      background-color: black;
      width: 50%;
      float: left; 
      
    }

    .right{
      background: linear-gradient(to left,#55524e, #171716);
      width: 50%;
      float: left;
      
    }

    .homeImage{
      max-width: 100%;
      height: 800px;
     

    }

    h1.mainH1{
      color: white;
      font-size: 2.5vw;
      display: flex;
      justify-content: center;

      margin-top: 1em;

      

    }


    h2.mainH2{
      color: white;
      font-size: 2vw;
      font-family: "Montserrat", sans-serif;
      display: flex;
      justify-content: center;
      margin-top: 20px;

    }

    .listItems{
      color: white;
      font-size: 1vw;
      font-family: "Montserrat", sans-serif;
      display: flex;
      justify-content: center;
      

    }

    .btnQuiz{
      
     font-family: "Montserrat", sans-serif;
      background-color: #ffe31c;
      border-radius: 10px;
      border: none;
      color: black;
      text-align: center;
      text-decoration: none;
      font-size: 16px;
      display: flex;
      
     
       margin: 0;
      position: absolute;
      top: 50%;
      left: 75%;
      -ms-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <main>
        <div class="row">

            <div class="column left"> <!-- Section on the Left side -->
                
                <img class="homeImage" src="images/barbell.jpg" alt="Man lifting barbell"> 
            </div>

            <div class="column right"> <!-- Section on the Right side -->
                <h1 class="mainH1">Welcome to the Fitness project</h1>
                    
                    <h2 class="mainH2">Here you can:<br></h2>
                    <br>
                    <ul>
                        <li class="listItems">Learn the fundamentals of fitness as well as diet</li>
                        <br>
                        <li class="listItems">Take a quiz to optimize the information for your goals</li>
                        <br>
                        <li class="listItems">Expand your knowledge with useful bodybuilding tips</li>
                    </ul>

                <button class="btnQuiz">Take Quiz</button>


                
                

            </div>

        </div>

        
    </main>

Answer №3

There are a couple of simple ways you can achieve this:

Option #1:

Add the following CSS properties to the class name 'right' for the column:

.right {
  display: flex;
  justify-content: center;
  align-items: center;
}

The above code will center all the content within your div with the class name 'column right'

Option #2

If you only want to center the button while keeping other elements unchanged, then wrap the button with a div container like so:

<div class='btn-wrapper'>
  <button class="btnQuiz">Take Quiz</button>
</div>

Next, apply the following CSS to the btn-wrapper in your stylesheet:

.btn-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

Answer №4

Consider utilizing

<center> <!-- insert button code here --> </center>

This method may be hardcoded, but it functions flawlessly.

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

Utilize JavaScript to automatically scroll to the element id of the current view

Is it possible to retrieve the name of an anchor tag in view as a user scrolls through an HTML page with multiple paragraphs and associated anchor tags? <p><a name="para1"></a> some long text </p> <p><a name="para2"> ...

Reduce / condense text that is overflowing

Take a look at the image I've attached. The text is overflowing outside the div, and I want to collapse it with a "Read more" link at the end. Users should be able to click on the "Read more" link to expand the text. I'm currently working on a p ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Trouble with clicking inner elements after applying JQuery code to parent div

Currently, I have implemented a code for toggling a search bar and it is functioning properly. The toggle function is applied to the main div using a click function in jQuery. While the toggling works fine, there seems to be an issue when clicking on the i ...

There seems to be an issue in AngularJS 6 with trying to read a property that is undefined, resulting in a TypeError

I keep seeing the error message "Cannot read property '0' of undefined". This snippet shows my HTML code: <!-- ... --> <img src="{{hit._source.productPhoto[0].docURL}}"> Below is a snippet of my JSON data: "hits": [ { "_inde ...

Ways to enhance the sharpness of an image when using transform scale

I noticed that when I use transform: scale(1.1); on hover for a specific element, the image appears blurry. Any suggestions on how to resolve this issue? Here is an example: https://i.sstatic.net/6zsky.jpg ...

Ways to ensure CSS affects icon inside main element?

Struggling to match the background color of Material-UI icons with the rest of the list items on hover. The CSS is not applying to both the icon and text despite styling the overall class (className= "dd-content-item"). Any assistance would be greatly appr ...

Tips for designing a chosen radio button with interactive space:

After stumbling upon this CSS query regarding styling selected radio buttons labels from Stack Overflow and also checking out this discussion on UX Exchange, I attempted to apply both techniques but couldn't quite get it right. It seems that a parent ...

What is the best way to utilize the isset method in PHP to check for the existence of two different

Having trouble with displaying both data sets in a PHP file? Here's the code snippet: <?php session_start(); include_once'config/connect.php'; //establish database connection if(isset($_POST['add'])) { $add = mysql_query( ...

Can django-rest-framework-filters be implemented with django-html to allow for querying using a "search" button on the initial server page?

When using Django filters, it becomes easier to retrieve specific data. For example, you can access data by typing in the URL like http:127.../api/?first_name=kiran (which will output data for first_name as kiran). You can also use URLs like http:127.0.0. ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

What is the best way to display a third DIV when two or more are already filled?

Looking to create a JavaScript function, primarily using jQuery, that shows a DIV only when specific DIVs are filled with content. For instance, If DIVs 1 and 2 have content (like two book titles in a list), then DIV three should appear for users to submi ...

Having trouble viewing the search field text in Firefox 3.6?

The customized search form in this version is inspired by the default twenty eleven Wordpress one. While the default text appears almost everywhere, it may not be displayed properly in older versions of Firefox and Internet Explorer. This could be due to ...

Adjusting the browser window height

I'm puzzled as to why setting the height viewport property like this: <meta name="viewport" content="width=480px, height=120px"> isn't effective. Even though window.innerWidth correctly reports 480px, window.innerHeight shows 210 instead ...

Poll # Warning: The variable "poll" has not been defined. Please check the code in H:xampphtdocsuserpollvote_form.php on

This is an HTML form for displaying a poll question. I am encountering errors with the variables 'poll' and 'question', as I am new to PHP. Can someone please assist me in resolving this issue? <html> <head></head&g ...

Unable to remove the initial item from my shopping cart

Currently working on my computing science assignment and decided to create an online store. I followed a tutorial to implement the shopping cart functionality, but I'm facing an issue. I can delete every item in the cart except for the first one that ...

What are the steps to utilizing mattooltip effectively?

Can someone help me figure out how to successfully implement mattooltip in this code? It's not working as expected. <div class="btn-edit-nounderline" matTooltipClass="custom-tooltip" (click)="edit(row.widgetAccess)" ...

How to modify the floating label color using Bootstrap 5

I'm currently utilizing bootstrap 5 to craft a form featuring floating input functionality. Below is an example of the input I am utilizing: <div class="form-floating mx-auto mb-3 w-25"> <input type="text" class=" ...

Drop-down menu with caret using HTML and CSS

Is there a way to include a dropdown caret for the account link in the html code provided below? . . . <nav> <ul id="menu"> <li class="home"><a href= "home.html" class="menu" >&l ...

Simple way to extract the values from every input element within a specific <tr> tag using JQuery

Is there a way to align all input elements in a single row within my form? For example, consider the snippet of code provided below, which includes a checkbox and a text input box. I would like to retrieve the values from both of these input types and pres ...