简体   繁体   中英

Center content of inline-block div elements

I try to do something like this in CSS/HTML:

例

Each “Box” should be a link to the details of the error. The text and the red div inside of the box should be horizontally centered, as shown in the image.

Here is my code: JSFiddle

.outerDiv {
    display: inline-block;
    border-radius: 10px;
    border: 2px solid #c3c3c3;
    height: 100px;
    width: 100px;
    margin: 5px;
}

.innerDiv {
    width: 50%;
    height: 100%;
    margin: 0 auto;
}

.errorLabel {    
    background-color: #a90329;
    display: inline;
    padding: .2em .6em .3em;
    font-size: 75%;
    color: #fff;
    border-radius: .25em;
    line-height: 1;
    vertical-align: baseline;
    font-weight: 700;
    text-align: center;
    white-space: nowrap;
    box-sizing: border-box;
}

Edit: After the answer of Fabrizio Calderan

If detected two small issue.

  • When the text of the label is very short it gets displayed on the same line as the text does.
  • When the text of the label is very long or contains as line break, the label doesn't look very good.

New JsFiddle

I was able to fix the first issue by turning the label into a block element. Now I'm looking for a way to make sure that all label have the same space to the bottom border. (It should look like the image, and not like the fiddle)

在此处输入图片说明

add a line-height to the inner div, eg line-height: 50px; and text-align: center to the outer div

http://jsfiddle.net/2mxud8uk/3/

.outerDiv {
    text-align: center;
    ...
}

.innerDiv {
    line-height: 50px;
    width: 50%;
    ... 
}

Result

在此处输入图片说明

I found a solution for my problem: JsFiddle

.outerDiv {
    text-align: center;
    float: left;
    border-radius: 10px;
    border: 2px solid #c3c3c3;
    height: 100px;
    width: 100px;
    margin: 5px;
    line-height: 50px;
}

.errorLabel {
  display:inline-block;
    vertical-align: bottom;
    margin-bottom:7px;
    width:84%;
    background-color: #a90329;
    padding: .2em .6em .3em;
    color: #fff;
    border-radius: .25em;
    line-height: 1;
    font-weight: 700;
    white-space: nowrap;
    box-sizing: border-box;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM