【问题标题】:How to center element inside of a div如何使div内的元素居中
【发布时间】:2013-07-28 07:07:39
【问题描述】:

我想将.SideBarFirst div的内容居中,但不知道如何实现。

有人可以帮我解决一个不是基于向元素添加 paddingleft/right 值的解决方案吗?

CSS:

body {
    width: 960px;
    margin: 0 auto;
} 

.content {
    width:500px; 
    float: left;
}

.SideBarFirst {
    width:460px; 
    float: right;
}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}

HTML:

<body>
    <div class="content">test</div>
    <div class="SideBarFirst">
        <div>not working for center</div>
    </div>
</body>

我当前的代码:http://jsfiddle.net/mmnaderi/yTCkx/

【问题讨论】:

  • 首先在正文中删除宽度和边距:0 auto
  • 这里有两种简单的方法可以让一个 div 中的元素居中,垂直居中,水平居中或两者兼而有之(纯 CSS):stackoverflow.com/a/31977476/3597276
  • 是的,显示表格和 flex 对于响应式网站来说不是安全的解决方案!示例:在显示表中显示一个大图像这个 div 比例和超过 100%。
  • 我的问题是为什么有时margin 0 auto inside off margin 0 autoworking但有时不工作???

标签: css margin center


【解决方案1】:

删除这个:

body {
    width: 960px;
    margin: 0 auto;
} 

使用这个:

HTML

<div class="content">test</div>
<div class="SideBarFirst">
    <div>not working for center</div>
</div>

CSS:

.content {width:500px; float : left;}

.SideBarFirst {width:460px; float : right;}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}

See This Fiddle

【讨论】:

  • 我看到你刚刚从正文中删除了 css
  • 我已经看过了,我知道你在编写代码时所做的更改 正文宽度和边距自动有什么问题
  • 其实我不知道。这是一种奇怪的行为:|
  • 哈哈,他没有做错任何事,他只是给身体宽度,这就是全部,根据 css 规则,它不是好的做法,请参阅我的评论,我已经在那里提到过
  • 为什么身体宽度有问题?
【解决方案2】:

您的问题是您将元素浮动到左侧,以便它始终出现在左侧。如果您想将其居中,请将您的 css 更改为:

.content {width:500px; float : left;}

.SideBarFirst {width:460px; float : right;}

.SideBarFirst div {
    width: 40px;
    margin: 0 auto; 
}

也删除这个:

body {
    width: 960px;
    margin: 0 auto;
} 

【讨论】:

    【解决方案3】:

    你可以使用 %

    .SideBarFirst div {
        width: 40px;
        margin: 0 50%; 
    }
    

    或者你可以更粗暴地试试这个:

    .SideBarFirst div {
        width: 40px;
        margin-left: 210px; 
    }
    

    弹性布局不适用于第二个代码

    或者这个:

    <div class="content">test</div>
    <div class="SideBarFirst">
        <div align="center">not working for center</div>
    </div>
    

    也看这个:How to horizontally center a <div> in another <div>?

    【讨论】:

      【解决方案4】:

      这是浏览器问题,现在已修复。

      【讨论】:

        猜你喜欢
        • 2013-02-13
        • 1970-01-01
        • 2023-01-24
        • 1970-01-01
        • 2018-07-08
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多