【问题标题】:CSS margins for elements with no width [duplicate]没有宽度的元素的CSS边距[重复]
【发布时间】:2016-08-26 17:02:57
【问题描述】:

我需要将一个没有宽度的 div 元素居中(它的宽度来自内部 div。

<html>
<head>
    <title></title>
    <style type="text/css">
    .outer {
        padding: 10px;
        /*margin: auto; (doesn´t work)*/
        background-color: #000;
        display: inline-block;
    }
    .inner {
        width: 400px;
        height: 400px;
        text-align: center;
        background-color: #CCC;
    }
    </style>
</head>
<body>

    <div class="outer">
        <div class="inner"></div>
    </div>
</body>
</html>

任何想法如何在不设置宽度的情况下解决此问题?

【问题讨论】:

  • body { text-align: center }

标签: html css centering


【解决方案1】:

你可以在 body 或 .outer 上这样做

这将使您的 div 水平和垂直居中对齐。

position: absolute; 
top:50%;
left: 50%;
transform: translate3d(-50%,-50%, 0);

【讨论】:

    【解决方案2】:

    对于水平居中,假定父级是相对的;

       .outer {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            padding: 10px;
            background-color: #000;
            display: inline-block;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 2016-05-02
      • 1970-01-01
      • 2019-11-05
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多