简体   繁体   中英

Vertically centering an element in referencing to the text in css

I have a background image in a <span> and I am trying to centralize the span in reference to the text regardless of the number of lines of the paragraph. Here is the link of the fiddle

HTML:

<ul class="leftlist">
    <li itemage="" id="1012" class="todo">
        <a href="#">           
            <span class="uncheck_box cb"></span>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vehicula lacus a nisi venenatis, sit amet tempor nunc mattis.</p>
        </a> 
    </li>
</ul>

CSS:

ul.leftlist {
    margin: 0 !important;
    width: 595px;
}
.leftlist ol, ul {
    list-style: none outside none;
    padding: 0;
}
ol, ul {
    list-style: none outside none;
    padding: 0 20px;
}
ol, ul {
    list-style: none outside none;
}
ul.leftlist li a {
    border: 1px solid #999999;
    display: block;
    font-size: 17px;
    min-height: 35px;
    padding: 10px 5px;
    text-decoration: none;
}
span.uncheck_box {
    background: url("http://i39.tinypic.com/22dtvp.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    display: block;
    float: left;
    height: 28px;
    margin: 4px 8px 10px;
    width: 28px;
}

I am assuming that you want to vertically center the grey box on the left of the paragraph (the <span> element) that is.

My solution involves:

  1. Taking the <span> element out of the document flow, positioning it absolutely
  2. Setting a left padding to the <p> element to make space for the grey box visually

The strategy is to use absolute positioning, but you will have to remember to set the parent to relative positioning. The element is then position at 50% from the top of the parent container (therefore vertically centering it), but you will also have to take into account the height of the element itself, which is by offsetting it vertically by half of its height (28/2 = 14px) with a negative top margin.

ul.leftlist li a {
    /* original style omitted for clarity */
    position: relative;
}
span.uncheck_box {
    background: url("http://i39.tinypic.com/22dtvp.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    display: block;
    height: 28px;
    width: 28px;
    position: absolute;
    top: 50%;
    left: 10px;
    margin-top: -14px;
}
ul.leftlist li a p {
    padding-left: 40px;
}

http://jsfiddle.net/teddyrised/8vjpj/1/

[Edit]: For validity, you might want to consider using HTML5 data- tags for attributes, like using data-itemage instead of just itemage .

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