使用css在div中居中多个元素 [英] Centre multiple elements within div using css

查看:178
本文介绍了使用css在div中居中多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用html和css,我正在尝试创建一个网站,代码部分如下:

I'm new to html and css and I'm trying to create a website, part of the code is here:

HTML:

<div class="row">
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
    <div class="circle"></div>
</div>
<div class="row">
    <div class="circle"></div>
</div>

CSS:

.circle
{
border-style: solid;
border-color: red;
width: 70px;
border-radius: 40px;
float:left;
margin: 2px;
}

.row
{
border-style: solid;
border-color: black;
height: 100px;
width: 700px;
margin: 10px;
}

http://jsfiddle.net/ubd9W/

我试图将红色圆圈(水平和垂直)黑盒子,但我似乎无法管理它。我试过使用'text-align'并将左右边距设置为自动,但这不工作。我也不能使用绝对定位,因为我有一个固定的菜单栏在页面的顶部,如果你滚动损坏。

I'm trying to centre red circles (horizontally and vertically) within the black boxes but I can't seem to manage it. I've tried using 'text-align' and setting the left and right margin to auto but that doesn't work. I also can't use 'absolute' positioning because I have a fixed menu bar at the top of the page and that gets ruined if you scroll.

任何帮助将是不胜感激。感谢

Any help will be greatly appreciated. Thanks

推荐答案

非常简单的理解与您提供的相同的代码只需要给父元素 align:center; position:relative;

very simple to understand with the same code you provide you just need to give the parent element a text-align:center; and a position:relative;

    .row{
        border:4px solid black;
        height: 100px;
        width: 700px;
        margin: 10px;
        text-align:center;
        position:relative;
    }

然后设置子 margin:10px auto; display:inline-block;

    .circle{
        border:4px solid red;
        height: 70px;
        width: 70px;
        border-radius: 40px;
       position:relative;
        margin:10px auto;
       display:inline-block;
    }

或如果您想要更多的边距,请更改 margin:10px auto ; margin:10px 40px;

or if you want more margin between them change margin:10px auto; to margin: 10px 40px;

demo: http://jsfiddle.net/ubd9W/14/

这篇关于使用css在div中居中多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆