How do you easily horizontally center a
usin

2018-12-31 04:55发布

This question already has an answer here:

I'm trying to horizontally center a <div> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div> element to be inline with rest of my page. I'll try to draw an example:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

标签: css html
22条回答
倾城一夜雪
2楼-- · 2018-12-31 05:52

If you know the width of your div and it is fixed, you can use the following css:

margin-left: calc(50% - 'half-of-your-div-width');

where 'half-of-your-div-width' should be (obviously) the half of the width of your div.

查看更多
只靠听说
3楼-- · 2018-12-31 05:52

Usage of margin-left:auto and margin-right:auto may not work in certain situations. Here is a solution what will always work. You specify a required width and than set a left-margin to a half of the remaining width.

    <div style="width:80%; margin-left:calc(10%);">
        your_html
    </div>
查看更多
梦该遗忘
4楼-- · 2018-12-31 05:52

I use div and span tags together with css properties such as block, cross-browser inline-block and text-align center, see my simple example

<!DOCTYPE html>
<html>
    <head>
       <title>Page Title</title>
       <style>
           .block{display:block;}
           .text-center{text-align:center;}
           .border-dashed-black{border:1px dashed black;}
           .inline-block{
                 display: -moz-inline-stack;
                 display: inline-block;
                 zoom: 1;
                 *display: inline;
            }
           .border-solid-black{border:1px solid black;}
           .text-left{text-align:left;}
        </style>
    </head>
    <body>
          <div class="block text-center border-dashed-black">
              <span class="block text-center">
                  <span class="block"> 
        <!-- The Div we want to center set any width as long as it is not more than the container-->
                      <div class="inline-block text-left border-solid-black" style="width:450px !important;">
                             jjjjjk
                      </div> 
                  </span>
              </span>
          </div>
      </body>
   </html>
查看更多
不再属于我。
5楼-- · 2018-12-31 05:53
.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

.divclass {
   min-width: 200px;
}

Then you can set your div to be

<div class="center divclass">stuff in here</div>
查看更多
登录 后发表回答