How can I center align text within div horizontally?

后端 未结 4 620
Happy的楠姐
Happy的楠姐 2021-01-24 13:08

This may be the stupid question,but I can\'t figure it out how to get this.

edit: I just want to center only text horizontally not the image and the image must be remain

相关标签:
4条回答
  • 2021-01-24 13:44

    Building on Afzaal Ahmad Zeeshan's answer...

    Put the text between 2 equal images. Set text-align:center on the containing div. This centers the image-text-image as a group.

    Then hide the second image.

    HTML:

    <div>
        <img src="http://placekitten.com/100">
        This works now.
        <img src="http://placekitten.com/100" class="cannot-see-me">
    </div>
    

    CSS:

    div {
        text-align: center;
    }
    
    img {
        width:30px;
        height:60px;
    }
    
    .cannot-see-me {
        visibility: hidden;
    }
    

    This works because visibility:hidden makes an element invisible, but it still takes up space on the page. So use that here instead of display:none.

    0 讨论(0)
  • 2021-01-24 13:50

    Get rid of the span and apply style="text-align:center;" to the div instead.

    0 讨论(0)
  • 2021-01-24 13:55

    change vertical-align:bottom to vertical-align:middle and set text-align:center to <div>

    jsFiddle

    <div style="text-align:center">
       <img style="width:30px;height:60px;
    vertical-align:middle;display: inline" src="http://placekitten.com/100">
       <span style="text-align:center;">This won't work.</span>
    </div>
    
    0 讨论(0)
  • 2021-01-24 14:02

    It you need to center it horizontally then use this

    div {
      text-align: center;
    }
    

    Have a look here! :) http://jsfiddle.net/afzaal_ahmad_zeeshan/Hyx5n/41/

    This way, all the elements inside the div (and not only the text) will be placed in the center. This way, you'll get the image in the center.

    0 讨论(0)
提交回复
热议问题