Centering an object within a grid width using PureCSS

1.1k views Asked by At

I have an html template that has PureCSS integrated into it so that I can start creating a layout. I have an object that is 20-24 width of a 24 split up grid. I have a form inside of the grid block it is in. I want to center the form content within that grid. I am not sure how to do that in an effective way. I tried adding my own css to override the pure css default but it is not working cna anyone help me. this is what I have for the html template:

<link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/build/grids-responsive-min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">

  <div class="pure-g">
    <div class="pure-u-lg-20-24 center-item-h">
      <form action="{% url 'searched' %}" method="POST">
        {% csrf_token %}
        <input type="text" name="searched" placeholder="Search">
      </form>
    </div>
  </div>

Here is the css that I tried to use to manually center the form in the block :

.center-item-h {
  margin-left: auto !important;
  margin-right: auto !important;
}

Here is what it looks like:

I got rid of the all the code of everything else that is not the block in question. I can add all the content if required to help solve this answer

1

There are 1 answers

3
Carl Edwards On BEST ANSWER

To horizontally center using margins you have to set a width to the element. Otherwise it won't know how to determine its' own spacing.

.center-item-h {
  margin: 0 auto;
  width: 50%; /* just an arbitrary amount */
}

Alternatively (and if you can), switch over to flexbox and just apply the horizontal alignment properties to its' parent:

.pure-g {
  display: flex;
  justify-content: center;
}