Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    83
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question How do I give images an absolute width while maintaining aspect ratio?

    I would like all images on a page to be the exact same width in pixels (say for this example, 300 px). What do I have to specify in CSS so that the images are all 300 px wide but still maintain their ratios with their heights?

    For example, say I have two images (a) 150 X 100 and (b) 600 X 1000. They should become (a) 300 X 200 and (b) 300 X 500. Please don't hesitate to ask for a clarification if you need one.

    Thanks!

  • #2
    Registered User
    Join Date
    Jun 2011
    Posts
    1,063
    Thanks
    12
    Thanked 241 Times in 240 Posts
    Quote Originally Posted by The Noob Coder View Post
    What do I have to specify in CSS so that the images are all 300 px wide but still maintain their ratios with their heights?
    It will automatically do that if you only set one dimension (width or height).

    Code:
    .something {
        width: 300px;
        /* no need for a height, it will maintain aspect ratio */
    }
    Code:
    <img src="" class="something" />
    Last edited by Sammy12; 09-14-2012 at 09:04 PM.

  • #3
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,478
    Thanks
    6
    Thanked 981 Times in 954 Posts
    Alternatively you can set height: auto; to override a previously set fixed height.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •