How do I center a div element horizontally in css?

How can I center div elements horizontally, so when I change the width of the browser, the last div is descended using css?

So:

---||||-||||-||||---

--------||||--------

      

When I write:

<div style="float: left; position: relative; left: 50%;">
  <div style="float: left; position: relative; left: -50%;">
    <div style="width:315px; height:340px; float: left; margin-top: 10px; margin-bottom: 10px;">Text</div>
    <div style="width:315px; height:340px; float: left; margin-top: 10px; margin-bottom: 10px;">Text</div>
    ...
  </div>
</div>

      

Then, after the element descends, all divs go left.

+3


source to share


3 answers


I would recommend using display: inline-block

for elements and then using text-align: center

in a container to handle your desired centering:

I cleaned up your HTML, but here is some basic HTML formatting with a class container

and multiple (as many) block

class DIVs:

<div class="container">
    <div class="block">Text</div>
    <div class="block">Text</div>
    <div class="block">Text</div>
</div>

      

CSS changes the display options of the blocks and the alignment of the text in the container:



div.block { 
  display: inline-block; /* this changes the elements to behave more like inline elements (think <span>s) */
  width: 315px; 
  margin: 10px 0; 
  height: 340px; 
}
div.container { 
  width: 100%; 
  text-align: center;  /* this is the magic that centers the elements */
}

      

I've put together a small demo to help you demonstrate this technique: JSFIDDLE Be careful, there is a small "quirk" with CSS . this results in little space between elements. This can be removed in a number of ways, my preferred methods are either using comments or completing the closing DIV tags. (problem caused by backspace / whitespace between elements in HTML):


display: inline-block

<div class="container">
    <div class="block">Text</div><!--
    --><div class="block">Text</div><!--
    --><div class="block">Text</div>
</div>

<div class="container">
    <div class="block">Text</div
    ><div class="block">Text</div
    ><div class="block">Text</div>
</div>

      

quirk behavior reference

+5


source


Create a container <div>

that is 100% of the given area. Then set each width <div>

inside the container to be% and float: left;

. They will stack next to each other until they fit and move on to the next line.



.container {
  width: 100%;
}
.three {
  width: 33%;
  min-width: 225px;
  float: left;
  border: 1px solid black;
}
      

<div class="container">
  
  <div class="three">
    <p>Something</p>
  </div>
  
  <div class="three">
    <p>Something</p>
  </div>
  
  <div class="three">
    <p>Something</p>
  </div>
  
</div>
      

Run codeHide result


Run snippet.

+1


source


You can use media queries to write different css code for different sizes:

Media queries

-1


source







All Articles